if we have MakeObject(String Name)
and calling this method will create Object [Name] = new Object();
How can we do that? And, if we want to move the Object [Name]
from the method to a public variable in class Clazz
?
Example:
public class clazz {
void MakeObject(String name) {
Object[name] = new Object();
[name].UpgradeToClassVariable(); // It should be a global variable
}
}
Usage of clazz
:
public class main {
public static void main(String[] args) {
clazz c = new clazz();
c.makeObject("Hello");
c.Hello.doOperations(); // For example, if it's a String, doOperation() can be equals()
}
}
In java, .
is the dereference operator: Take the thing to the left of the 'dot'. This must be a reference. If it is a reference to nothing (null), a NullPointerException occurs.
The thing to the right is the message you send to it.
Thus, sending an object the message 'make yourself global' doesn't make any sense. Something like MyClass.makeGlobal([name])
would, but java doesn't support this.
A class's structure is defined at compile time. You cannot, at runtime, add properties, or change a field from being instance to static.
The general idea of 'I want to add a property' still exists, but, not at the level you're talking about. Perhaps you want a Map<String, Integer>
for example.
Take your second snippet:
clazz c = new clazz();
c.makeObject("Hello");
c.Hello.doOperations(); // For example, if it's a String, doOperation() can be equals()
That's just not how java works. Java will first compile code ( javac
), and then run it. javac does not run any code , it only compiles it. Thus, javac sees c.Hello
and stops you right there, and says: Hello? What? I have no idea what you're talking about.
That's why it is not possible to use a string literal to make a field like this.
Java isn't javascript, or python, or ruby.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.