2

Suppose I want to create a Java object from string.

Object obj = Class.forName("com.my.object.MyObject").newInstance();

I was able to create MyObject. My question is how can I create a Java built-in object such as Long or String from string. I need to do this because I can only know the type of object in run time in text format.

I did this but didn't work.

Object obj = Class.forName("java.lang.Long").newInstance();
3
  • As an aside: even though it's obvious to most people who can answer this question why your second code sample didn't work, you should avoid only saying "this didn't work" on SO. Give us the stack trace and error message. And preferrably look at the error message and see if it helps you resolve the error. Commented Apr 24, 2013 at 17:33
  • (Okay, the error in this case is pretty damn useless, but still.) Commented Apr 24, 2013 at 17:45
  • Thanks for comment. I will add more detailed error message next time. Commented Apr 24, 2013 at 18:07

2 Answers 2

12

java.lang.Long does not have a no argument constructor, so you can't call newInstance like that. Instead, you have to look up the constructor with the correct arguments, build the argument array, and then invoke the Constructor.

Constructor constr = Class.forName("java.lang.Long").getConstructor(String.class);
Object myLong = constr.invoke("5");
Sign up to request clarification or add additional context in comments.

Comments

4

Read the documentation for newInstance(), it will tell you that it calls the no-parameter constructor of a class. If the built-in (or any other) class has such a constructor, you can create it just the same. Otherwise, you'll have to call the specific constructor by using Class.getConstructor(), and pass it the appropriate parameters. So, to call the new Long(String) constructor for example:

Class.forName("java.lang.Long")
     .getConstructor(String.class)
     .newInstance("12345");

Comments

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.