0

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.

2
  • 1
    As written, the answer is no (you can't create variables at runtime). But there's probably an answer. What is the actual problem that you're trying to solve? Commented Jan 13, 2011 at 14:33
  • nope, it's just some of my experiment with java.I'm new to java and i found out that it's really great! Commented Jan 13, 2011 at 14:38

3 Answers 3

2

You can do this:

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

But it won't work for primitive types.

Sign up to request clarification or add additional context in comments.

4 Comments

which, in a pinch, could still be used for the wrapper classes around the primitive types.
It should work fine for boxed primitives, i.e. Integer, Double etc (as opposed to int and double).
i guess this is the final solution.
@Singgum3b - assuming that the class you want to instantiate has a no-arg constructor. Value classes (eg: Integer) don't, so this code will throw. Like I said above, the correct answer depends on the actual problem that you're trying to solve. In most cases, rather than reflection, I'd use a factory.
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. 

}

Comments

0

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.

1 Comment

Integer doesn't have a no-arg constructor, so this code will throw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.