Truong Nguyen
Truong Nguyen

Reputation: 86

Indicate datatype from a input string?

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.

Upvotes: 0

Views: 144

Answers (3)

Qwerky
Qwerky

Reputation: 18445

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.

Upvotes: 0

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. 

}

Upvotes: 0

dogbane
dogbane

Reputation: 274612

You can do this:

String className = "MyClass";
Object obj = Class.forName(className).newInstance();

But it won't work for primitive types.

Upvotes: 2

Related Questions