java


Java: calling an object using a generated string


I would like to call an object through the use of a generated string.
As you can see, name is being generated correctly.
Also, the method for getting the object works fine.
However I can not use name to reference the object even though that is the name of the object.
Why is that? How can I solve this?
public class FrameTest{
public static void main(String[] args) {
ObjectMethod first_object = new ObjectMethod(); //instanciate object
first_object.setCost(2.5);
String object = "first";
String one = "object";
String name = object + "_" + one;
System.out.println(name);
System.out.println(first_object.getCost());
System.out.println(name.getCost()); //this line does not work
}
}
public class ObjectMethod{
public double value;
public void setCost(double cost) {
value = cost;
}
public double getCost() {
return value;
}
}
The closest I can think of to what you're describing, short of using Reflection (if you're asking this question, you're not ready for Reflection) is to have a map of strings to objects.
Map<String,Runnable> options = new HashMap<>();
options.add("getCost", new CostGetter(...));
options.add("getDescription", new DescriptionGetter(...));
String command = getCommandFromUi();
options.get(command).run();
It could be Callable rather than Runnable. It could be an interface of your own. In Java 8 it could be Supplier and you could pass lambdas:
options.add("getCost", () -> currentUser.price());
Have a look at the Command and Strategy patterns in any book about design patterns.
You have to understand: Java isn't ruby or python or some other dynamic language.
There is no magic connection that allows you to turn a reference to a String into something else.
In other words: the fact that you put "object_one" into a string object doesn't allow you to treat that String like some actual variable object_one.
The one feature of Java that goes into that direction is reflection. But that is really an advanced topic; and before you look into that, you should understand the real basics of Java. So, better start here.
What I mean is: as the answer by "slim" points out: you could use a Map in order to implement some sort of "call by name" functionality. But the point is: that is "not how you do things in Java". Java is a statically compiled language; and there is no sense in using Java when one then tries to break out of that system and do things that rely on flat string parsing at runtime.
This will not work as you wish, because you are trying to call getCost() on String name object.
name - is just a string, but not the object of ObjectMethod class.
You cannot invoke name.getCost() and type of name is String, and string donot have getCost() method. Hence, your code fails here.
String name = object + "_" + one;
In above code, you are assigning name field with value "object_first". That means, field name is type of String with value "object_first". So, name is in no way related to ObjectMethod class, and hence name.getCost() make no sense.
Basically, what you are trying to accomplish
"I would like to call an object through the use of a generated string"
is not possible unless you use reflection.
java is a Strong typed language
that means you have to define a variable and also specify the variable type before you use it and (emphasis mine)
Certain operations may be allowable only to that type*
just because you do:
String objectName;
Object comboValue = departingStop.getSelectedItem();
Object combo2Value = finalStop.getSelectedItem();
objectName = comboValue + "_" + combo2Value;
dosn't mean that now objectName mutated from string into a ComboBox...
imagine how terrible this could be:
Car tata = new Car();
Robot kuka = new Robot();
String foo = tata.getName() + kuka.getName();
now what is foo? a transformer?? NO,
is still a String...
since that is a string you just can not do
foo.drive(), because is not a car, neither foo.weld(); because is not a robot

Related Links

Breadth-First-Search for moving dot game
Splitting string from file
Recursive Fibonacci code
Class structure for Top Trumps card
REST url #RequestParam encoding cannot be decoded to proper format (Spring MVC)
Searching for a better method for zig-zag array
Error when try to add map inside fragement TAB
Replacing a class with another using Eclipse Transforms: can't fix ClassFormatError
Jaybird (Firebird JDBC) ResultSet FetchSize — Pagination long lasting queries
how to use an array or an ArrayList with indices bigger than Integer_Maximum_Value? [duplicate]
Seed, Random number, and bound using java.uitl.Random
java.sql.SQLException: ORA-01843: not a valid month (Working in SQL DEVLOPER and dosen't work in JAVA)
How to run java for loop in parallel?
Query dsl returning duplicate records on #one to many association(leftJoin vs leftJoin.fetch vs fetchAll)
How to mock a protected static inner class with PowerMockito
using yaml in spring boot

Categories

HOME
deployment
single-sign-on
sd-card
jira
google-oauth
cmd
yarn
microservices
directx
portia
virtualization
facebook-php-sdk
metatrader4
wheelnav.js
event-handling
quickfix
jsprit
worldwind
telephony
google-static-maps
aurigma
apache-metamodel
evopdf
openedx
viewport
jprofiler
dbext
riot.js
autosys
trading
microsoft-sync-framework
bootstrap-duallistbox
web-api-testing
fabric8
google-sites-2016
google-qpx-express-api
caret
accelerate-framework
amazon-kinesis-kpl
force-layout
plsql-psp
suricata
main
libraries
streamsets
squib
estimote
wso2carbon
smartcontracts
youcompleteme
hibernate-tools
pango
prolog-setof
alphabet
mplayer
nstextview
recursive-datastructures
lift-json
windows-iot-core-10
mako
arrow-keys
lync-client-sdk
watchconnectivity
wdf
azure-sdk
django-debug-toolbar
lttng
persist
essence
packagist
design-by-contract
revolution-r
pyke
iad
cyclomatic-complexity
jmeter-maven-plugin
sankey-diagram
vstest.console.exe
cisco-ios
sonarqube5.1.2
device-orientation
operator-precedence
c3
camanjs
codeigniter-routing
onactivityresult
undefined-reference
datagridviewcolumn
monomac
uv-mapping
shellexecute
qt-faststart
eventual-consistency
jquery-mobile-dialog
android-screen-support
clipper
itmstransporter
e4x
dmoz
cisco-jtapi
getmessage
gamma
dbal
compiler-specific
mtj
boost-smart-ptr

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile