For example i have a string input "int",can i declare a variable base on that input? (Not switch check please开发者_运维知识库). I mean something like this (pseudo-code) or similar:
String str="int";
new (variable_name,"int");
// create new variable with int datatype.
You can do this:
String className = "MyClass";
Object obj = Class.forName(className).newInstance();
But it won't work for primitive types.
If instead of using primitive types you will use cannonical name of Object based class you can try to do this
public Object loadClass(String className) {
return Class.forName(className).newInstance(); //this throw some exceptions.
}
Not practically, Java is strongly typed and the type of all variables must be known at compile time if you are to do anything useful with them.
For example, you could do something like this;
String str = "java.lang.Integer";
Class clazz = Class.forName(str);
Object o = clazz.newInstance();
..which will give you an Object
o whose type is determined at runtime by the value of the String
str. You can't do anything useful with it though without first casting it to the actual type, which must be known at compile time.
精彩评论