How to create a variable name at runtime? - java

I am not able to create the name of the object at runtime. My statement is:
Map<String,String> objectName+""+lineNumber = new HashMap<String,String>();
It's giving me compiletime error. I want to create the HashMap object at runtime depending upon the line number.

Java is not a interpreted but rather a compiled language. So the compiler does not knows how to handle this. Such a thing might make sense in a scripting language.
If you need a custom Name for a "variable" maybe a construct like the following might make sense:
Map<String,Map<String,String>> varMap = new HashMap<String,Map<String,String>>();
varMap.put(objectName+" "+lineNumber, new HashMap<String, String>());

You can't do this directly in Java (without major tricks)
What you can (and probably should) do:
Put your Map in another map which has the 'variable' name as a key.
If you really want to do that you have to do code generation. For this again you have multiple options:
Generate Java Source Code and compile it
Generate Java Byte Code on the fly. You might wanna look at this list: http://java-source.net/open-source/bytecode-libraries for libraries available.

Having a dynamic object name is of No Use.
At first, it's not possible to give reference a dynamic name. The bigger question is Why do you want to do it?
If, just for learning and doing experiments, I'll suggest you should follow proper exercises.
But, if you are trying to achieve some project requirement, Pls. explain the requirement. There will be some other way to achieve that.

Related

How to convert ArrayList to ExampleSet in Rapidminer?

I'm creating an extension for rapidminer using java. I have an array of elements of type Example and I need to covert it to a dataset of type ExampleSet.
Rapidminer's ExampleSet definition looks like this:
public interface ExampleSet extends ResultObject, Cloneable, Iterable<Example>
I need to pick certain elements from dataset and send it back, still as ExampleSet, however casting is not working and I can't simply create new ExampleSet object since it's an interface.
private ExampleSet generateSet(ExampleSet dataset){
List<Example> list = new ArrayList<Example>();
// pick elements from sent dataset and add them to newly created list above
return (ExampleSet)list;
}
You will need more than a simple explicit cast.
In RapidMiner, an ExampleSet is not just a collection of Example. It contains more complex information and logic.
Therefore, you need another approach to work with ExampleSets. Like you already said, it is just the interface, which lead us to choice of the right subtype.
For starters, (Since: 7.3) simply use one of ExampleSets class's methods .
You also need to define each Attribute this ExampleSet is going to have, namely the columns.
Below, I create one with a single Attribute called First
Attribute attributeFirst = AttributeFactory.createAttribute("First", Ontology.POLYNOMINAL);
ExampleSetBuilder builder = ExampleSets.from(attributeFirst);
builder.addDataRow(example.getDataRow());
ExampleSet result = builder.build();
You can also get the Attributes in a more generic way using:
Attribute[] attributes = example.getAttributes().createRegularAttributeArray();
ExampleSetBuilder builder = ExampleSets.from(attributes);
...
If you have many cases where you have to create or alter ExampleSet, I encourage you to write your own ExampleSetBuilder since the original implementation have many drawbacks.
You can also try searching for other extensions, which may already meet your requirements, and you do not need to create one of your own (belive me, it's not Headache-free).
the ExampleSet class is getting deprecated (but still perfectly fine to use).
You might want to consider switching over to the newer data set API called Belt (https://github.com/rapidminer/belt). It's faster and more intuitive to use. It's still actively developed, so feedback is also welcome.
Also if you have more specific questions, feel free to drop by the RapidMiner community (https://community.rapidminer.com/), where also many of the developers are very active.

Get variable name of object from an ArrayList

I am creating an ArrayList of JTextFields using the following code.
ArrayList<JTextField> cmp = new ArrayList<>();
cmp.add(txtAmount);
cmp.add(txtBillTo);
cmp.add(txtBranch);
After passing this ArrayList into a method, I need to print the "variable name" of the textfield. I can use the SetName and GetName to print some names. But I need the output as txtAmount, txtBillTo, txtBranch.
Is there anyway to find the variable name of textfield?
No, you can't do this. The information you are asking for is just not recorded. The only way to do it would be to store it yourself:
Map<String, JTextField> cmp = new HashMap<>();
cmp.put("txtAmount",txtAmount);
cmp.put("txtBillTo", txtBillTo);
cmp.put("txtBranch", txtBranch);
If you need to keep things in the same order you put them into the collection then use a LinkedHashMap instead of a HashMap as the HashMap may change the order.
What you are looking for would require reflection of method code, something supported by languages such as Scala via macros/compile time reflection. However Java itself does not support runtime or compile time reflection of method code, only runtime reflection of classes/fields/functions, although some people have pulled together their own Java parsers to grab the information from source files and others have pulled the information from the Class files debug information. Neither of which has an officially supported API.
Your best bet is to place the name that you want along with the field, which is obviously duplication and thus could diverge by accident but your options are limited.

Java statically defined dictionary / HashMap

I have a block of static data that I need to organize into an array containing hash maps. Specifically, I want to have a static object in my app that contains the time zone information like this: https://gist.github.com/pamelafox/986163
Seeing how clean the definition looks like in Python, and knowing how a similarly clean definition can be created with some of the other languages I know, I was hoping there is a cleaner approach to it in Java then just running map.put(...) repeatedly. I have seen this question: How to give the static value to HashMap? but what wondering if there is a better way to do it?
One solution would be to store the data as a normal string in whatever format you can think of and then convert the string representation into the map (static, non-static or as a one-time initialized instance).
An improvement of this method would be to store the data in a file and load it (can be included in .jar package, when you use jar). This solution would have the advantage that data can be easily updated.

Java: How should I store thing per-user in memory

I need to store values specific to a username into memory, I was thinking about something like dynamically naming vars, so that I could do something like
["bubby4j_falling"] = true;
and index it by
["bubby4j_falling"]
But, this is just a example, I know that won't work, I just want a way to quickly and simply get and store things dynamically.
You want to use a Map with string keys, for example a HashMap<String, something>.
Your example would look like this:
Map<String, Boolean> map = new HashMap<String, Boolean>();
map.put("bubby4j_falling", true);
if(map.get("bubby4j_falling")) {
...
}
Actually, in your case a Set<String> would be more useful:
Set<String> fallingUsers = new HashSet<String>();
fallingUsers.add("bubby4j");
if(fallingUsers.contains("bubby4j")) { ... }
But uf you already have User objects (and you should), you should better use a Set<User>, or even let this falling simply be a property of the user object. Then you could have a Map<String, User> to get the user objects by name.
#PaĆ­lo Ebermann's answer is spot on.
I just want to point out that the Java language has nothing that resembles a dynamic variable. All Java variable names and their types are declared in the Java source code. Not even reflection will allow you to create new variables on the fly in an existing class.
Java is designed as a static programming language, and it works best if you use it that way.
(In theory, if you mess around with source code or byte code generation technologies, you can dynamically create a new class with new variables. However, this involves a HUGE amount of work, and not something that a sensible programmer contemplate doing to solve a simple problem. Besides, I doubt that this approach would actually help in your particular case.)

New classes created by users?

Consider this situation: I've got an aquarium simulator where I have 5 different types of fishes. Different types means different attributes (speed, colour, hunger, etc). What if I want the user of my simulator to be able to create a new type of fish and give it its values for its attributes?
How is that implemented by the programmer? Do I need some kind of "event handling" that will add a specific bunch of lines of code in my "Fish" class? Is that even a valid thought?
(In case it's essential, the language is Java. And to avoid any misunderstandings and prevent comments like "is this uni work?", yes it is. But I am not looking for THE answer, I am curious about the concept.)
EDIT: Yeah, my bad that I didn't mention the interaction way: a GUI.
So, imagine a tab called "Add New Species" that has a field for every attribute of the fishes (type, speed, colour, etc). So, the user fills in the fields with the appropriate values and when he clicks on "add" the constructor is called. At least that's how I imagine it. :)
I would just use a map:
class Fish
{
Map<String,String> attributes = new HashMap<String,String>();
setBusterFish()
{
attributes.put("speed", "5");
attributes.put("colour", "red");
attributes.put("hunger", "10");
attributes.put("name", "buster");
}
}
Java is an OO language, and it deals in classes and objects. The tempting, naive solution would be to have your program deal with "classes" of fish like it deals with classes of anything, i.e. to create some Java code and let the compiler and loader introduce it into the runtime.
This approach can be made to work, with some awkwardness. Essentially your "dynamic Java classes" coding would probably end up much bigger and complicated than your assignment actually intends.
You only really need to do this if you are actually going to have different attributes (not just different values of those attributes) for your different fish; and even then there are simpler solutions.
For what's being asked, I think you really only need one Fish class. When the user defines a new one, what he's really defining are the attribute values.
If you really want new and dynamic attributes, then you could go a long way using e.g. a HashMap to store name/value pairs. You could let the user add "legs" / "4" and then print out that new attribute as-is; but you couldn't make the fish walk on those legs because you'd be missing coding to work with the new attribute.
Have a look at the type object pattern. Also google for it I just gave one of the first references I found...
You may also look the Reflection pattern...
Let the user define attribute values of an instance of, say, a FishSpecies class, and give the FishSpecies a method createFish that creates a fish of that species (i.e. having those attribute values). Keeping track of all FishSpecies objects in a list grants you the opportunity to manage FishSpecies objects, and create Fish objects of given species.
If I understand your question correctly, then I believe that complicating things more than this is a mistake.

Categories

Resources