Is there any way to create the name of an object depending on user input?
eg.
Object scan.nextLine() = new Object();
No it is not possible. There are no dynamic variables in Java. Java variable name have to be declared in the source code during compile time.
If want to store the Object with the user entered values you can try using a Map to save the data as below.
Map<String, Object> objects = new HashMap<String, Object>();
String name = scan.nextLine();
Object obj = new Object();
objects.put(name, obj); // saving the objects in Map
No you can't do this.
I would suggest having a custom class and store the instanceName:
public class MyClass {
private String instanceName;
public MyClass(String instanceName) {
this.instanceName = instanceName;
}
}
MyClass myObj = new MyClass(scan.nextLine());
No. You cannot do that in java. Since you should already have a class defined to create a object of it.
There are some ways you could fake doing this. You could use a map to give the perception of dynamically named Objects. But since you say you are a beginner, the short answer is no. Make sure you know what you are asking for in your example though. Your example is the equivalent of saying:
String line = "foo";
Object line = new Object();
My guess would be that's not what you wanted (and isn't possible).
Given the line
Type variable_name = expression ;
The name variable_name is simply used in the rest of the scope for referencing the outcome of expression. You know that Java is a compiled language, and these names are only useful to the programmer. Once the compiler does its job, it can use a translation table and replace those names with whatever ID it wants.
Since those name don't even exist at runtime, there's no way of choosing the name for a variable at runtime.
However you may need to access an object depending on user input (for example like in PHP variable variables $$a_var). Depending on your context, you may use reflection to access instance members, or a simple Map<String, Object>. Example with reflection:
public class VariableRuntime {
static class Person {
public String first, last, city;
}
public static void main(String[] args) throws Exception {
Person homer = new Person();
homer.first = "Homer";
homer.last = "Simpson";
homer.city = "Springfield";
System.out.println("What do you want to know about Homer? [first/last/city]");
String what = new Scanner(System.in).nextLine();
Field field = Person.class.getDeclaredField(what);
System.out.println(field.get(homer));
}
}
The same with a Map<String, String>:
public class VariableRuntime {
public static void main(String[] args) throws Exception {
Map<String, String> homer = new HashMap<String, String>();
homer.put("first", "Homer");
homer.put("last", "Simpson");
homer.put("city", "Springfield");
System.out.println("What do you want to know about Homer? [first/last/city]");
String what = new Scanner(System.in).nextLine();
System.out.println(homer.get(what));
}
}
Related
I'm wondering if I can declare an object in-line in Java like I can in JavaScript.
For example, in JavaScript I could say
let nameOfObject = {
anyKey: "my value",
someOtherValue: 5
};
console.log(nameOfObject.anyKey);// This logs "my value"
and this will create a classless object and assign nameOfObject as its "pointer" of sorts... How can I do this in Java? How do I create an object without a class?
I found one possible solution which looks like
Object nameOfObject = new Object(){
public String anyKey = "my value";
public int someOtherValue = 5;
};
System.out.println(nameOfObject.anyKey);
But that doesn't seem to compile, and says "anyKey cannot be resolved" and according to some other sources, will not work at all...
So I might be doing something very wrong, or maybe there's a different method, or maybe it's just straight up not possible with Java and I need to do it a different way...
class Some{
public String anyKey;
}
Some some = new Some() {
this.anyKey = "my value";
};
This code throws an error saying Syntax error, insert ";" to complete declaration, however
class Some{
public void anyMethod() {
}
}
Some some = new Some() {
public void anyMethod() {
System.out.println("Okay");
}
};
Works perfectly fine?
I don't understand what's going on here, but I would really appreciate an explanation and/or a solution (if one exists).
You can't really think of it as an "object" in Java. JavaScript objects are unique implementations of HashTables. If you want similar functionality, you can use a Java HashMap or ConcurrentHashMap(HashTable), depending on your specific requirements.
// we only add String->Double, but since you want to add "any type",
// we declare Map<Object, Object>
HashMap<Object, Object> map= new HashMap<>();
map.put("Zara", new Double(3434.34));
map.put("Mahnaz", new Double(123.22));
String[] names = map.keys();
while(names.hasMoreElements()) {
str = (String) names.nextElement();
System.out.println(str + ": " + map.get(str));
}
So, all objects in java have a class associated with them. Even raw Objects have a class: The Object class! You won't be able to create an object without a class because all values need to have a type of some sort. But that's really not a huge problem. If you need an object that stores certain values, you can just create a class that has space for those values. There's really no situation where you would not be able to do this.
That being said, if you just want a way of mapping keys to values, I'd recommend looking into the Map data structure.
JavaScript classes are different from Java classes, JavaScript is not a class-based object-oriented language, an object in JS is used as a template to hold properties, but in Java classes could hold variables (properties) and functions, so to initialize an object in Java there has to be a class for that object, you can think of it as a blueprint of how the object will be initiated for example to create a class:
public class Example {
public String link = "https://stackoverflow.com/";
public void printLink() {
System.out.println(link); // Prints the string stored in link
}
public void openLink() {
// Some code to open the link in the browser
}
}
To initialize an object from the class you created call this in your main or somewhere where the code will run:
Example example = new Example();
example.printLink(); // Printed the link
example.openLink(); // Opened the link
example.link = "https://example-link.com/"; // Changed the link
Note that the Example class could be in a different file and the file name has to be the same as the class name, here it is (Example.java)
Anyway if you are looking for an equivelant for JavaScript classes HashMap or HashTable could be very close.
I have method getMap(String name, Integer value) so inside method i'm creating new HashMap() object, but i want HashMap() object reference name as String name value
Here is my code, i know i should not do like this because name is String type, but just to show
public static void main(String[] args) {
getMap("refMap", 10);
}
public static void getMap(String name, Integer value) {
Map name = new HashMap<>(); // Compile Error duplicate local variable
//Map refMap = new HashMap<>(); i want like this
}
Is this possible?
I'm assuming you know about HashMaps because of the code you have listed. You can use HashMaps to associate String values to specific objects which serves a similar purpose as naming the object as the String value parameter.
Check out this answer: Creating a variable name using a String value
I have a question, i have a code like below:
controller.start(c.class, 1);
but i want to set "c" from console. I can get/set it from args on main method . but how can i put it on c.class ? I mean how can i do that?
String a = "c";
controller.start(a.class,1);
Of course it doesnt work , but i hope i can tell u about my problem
On php we can use $$string to set/get string to variable, but i dont know how can we do it on Java ?
More commonly used (and more secure) way of addressing this is using maps:
private static final Map<String, Class<?>> NAME_TO_CLASS = new Map<>();
static {
NAME_TO_CLASS.put("c", c.class);
...
}
static void main(String[] args) {
...
controller.start(NAME_TO_CLASS.get(args[0]), 1);
}
Of course in real life you'd want to check if argument is correct and is in the map NAME_TO_CLASS.contains(your_arg);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamic Variable Names in Java:
Let's say I have a string, as below.
String s = "Hello";
Now, I want to create a string, but the string's variable will be called "Hello". In order to make the string's name "Hello", I must access string s to get the name "Hello", so I can use it as a variable name. Below is what I want to see.
String Hello = "I want to do this, But from Accessing String s So I KNOW that String s = Hello";
Thank you for the effort, and please try to explain to me because I am a Java beginner. :D
What you are attempting to do is add a layer of indirection. You cannot access variables dynamically in a static language such as Java/C/C++/Pascal/etc
What you can do is emulate the dyamic context that dynamic languages use by, eg creating a Map to hold the variable names and values in this case you would have
Map<String,String> stringVars = new HashMap<String,String>();
// set a "variable"
stringVars.put("Hello", "value");
// get a "variable"
System.out.println(stringVars.get("Hello"));
Using Reflection (not recommended):
public class MainClass
{
public String Hello = "I want to do this, But from Accessing String s So I KNOW that String s = Hello";
public static void main(String[] args) throws Exception
{
MainClass m = new MainClass();
String s = "Hello";
String result = (String) MainClass.class.getField(s).get(m);
System.out.println(result);
}
}
OUTPUT:
I want to do this, But from Accessing String s So I KNOW that String s = Hello
Instead, use a map as others illustrated.
It is not possible in java.
The only thing you can do is to use A map interface' implementation, for example a HashMap. Using a put method you can 'assign' a value to a given 'name'. The name would be a key and has to be unique within a map, just like variable has a unique name within it's scope.
To retrieve the value, call get method passing appropriate key (ex. string 'Hello') as an argument.
In Java you cannot obtain the variable(reference) name which is pointing to an object since the object has no knowledge of the reference to it and there can be more than one variable refering to the same object.
On the other hand you could do somtething like this; but I do not know how would help:
String s = "Hello";
Reference<String> hello = new SoftReference<String>(s);
String myStringAccessedWithHello = hello.get();
Could you use a Map which takes a string (such as "Hello") and maps it to another String (such as "I want to do this, But from Accessing String s So I KNOW that String s = Hello"). Something like the following:
Map<String, String> stringMap = new HashMap<String, String>();
stringMap.put("Hello", "I want to do this, But from Accessing String s So I KNOW that String s = Hello");
Then you can find all of the key values in the map (such as "Hello") by calling:
Set<String> stringKeys = stringMap.keySet();
and you can lookup the long string belonging to the key "Hello" like this:
String longValue = stringMap.get("Hello");
This is how I would use a simple String value to find an unwieldy String value. Bear in mind you could also use a Map which maps String values to any other type of object.
I'm trying to create a class that can instantiate arrays at runtime by giving each array a "name" created by the createtempobjectname() method. I'm having trouble making this program run. I would also like to see how I could access specific objects that were created during runtime and accessing those arrays by either changing value or accessing them. This is my mess so far, which compiles but gets a runtime exception.
import java.lang.reflect.Array;
public class arrays
{
private static String temp;
public static int name = 0;
public static Object o;
public static Class c;
public static void main(String... args)
{
assignobjectname();
//getclassname();//this is supposed to get the name of the object and somehow
//allow the arrays to become updated using more code?
}
public static void getclassname()
{
String s = c.getName();
System.out.println(s);
}
public static void assignobjectname()//this creates the object by the name returned
{ //createtempobjectname()
try
{
String object = createtempobjectname();
c = Class.forName(object);
o = Array.newInstance(c, 20);
}
catch (ClassNotFoundException exception)
{
exception.printStackTrace();
}
}
public static String createtempobjectname()
{
name++;
temp = Integer.toString(name);
return temp;
}
}
Create a Map then you can add key/value pairs when the key is your name and the value is your array.
Following up from #Ash's answer, here is some illustrative code. Notice that there is no reflection involved.
Map<String, Object> myMap = new HashMap<String, Object>();
...
Object myObject = ...
myMap.put("albert", myObject); // record something with name "albert"
...
Object someObject = myMap.get("albert"); // get the object named "albert"
// get("albert") would return null if there nothing with name "albert"
EDIT I've edited the example to use the type Object, since that is more closely aligned with what you are trying to do (I think). But you could use any type instead of Object ... just replace the type throughout the example. And you can do the same with an ArrayList; for example:
List<Date> dates = new ArrayList<Date>();
dates.add(new Date());
Date firstDate = dates.get(0);
Notice that no typecasts are required.
I expect you're getting a ClassNotFoundException from this line:
c = Class.forName(object);
The value of object the first time it's called is "1", which is not a valid class name.
Class.forName requires a class name as input, such as "java.lang.Integer". Trying to "name" your array in this way doesn't make sense to me. You need to pick an appropriate Java class name.
If you want to "name" an array instance (after you've created it), you could always store the instance as the value in a Map, using the name as the key.