Home How to use return of "Class.forName(String)" as a type for variable?
Reply: 2

How to use return of "Class.forName(String)" as a type for variable?

Piotr Osada
Piotr Osada Published in 2017-09-11 11:22:52Z

How to use return of "Class.forName(String)" as a correct type for variable? I mean, for example - if I am getting class using:


how to use it as "String" like:

String something = "text";

?? Thanks for any help! :)

Jacek Cz
Jacek Cz Reply to 2017-09-11 11:33:32Z

Demo and few words, but I dont assume this have practical sense for You. My goal is to give very basic background, more complicated answers arrive too.

Object instance = null;
 Class clazz = Class.forName("java.lang.String");
// now here is String.class

  instance = clazz.newInstance();
  // empty String as Object
}catch(Exception e)

After this code instance will have empty String (accessible as Object, not too useful) In general many thing can go wrong, maybe class have not no arguments public constructor etc


AxelH Reply to 2017-09-11 11:34:34Z

Here is how to create a String instance using Reflexion.

String s = (String) Class.forName("java.lang.String")
                         .newInstance("Foo bar");

This will recover a Class using Class.forName(String)

From this class, you get a specific constructor that accept a Class<?>... (0..N parameter) using Class.getConstructor(Class<?>...). And then you create the instance passing the paramter value using Constructor.newInstance().

This is not safe, you have a lof of exception to catch from this, but this will do it.

You can use directly Class.newInstance but it need to have an empty constructor available.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.366148 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO