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
1#
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:

Class.forName("java.lang.String");

how to use it as "String" like:

String something = "text";

?? Thanks for any help! :)

Jacek Cz
2#
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;
try{ 
 Class clazz = Class.forName("java.lang.String");
// now here is String.class

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

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

https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance()

AxelH
3#
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")
                         .getConstructor(Class.forName("java.lang.String"))
                         .newInstance("Foo bar");
System.out.println(s);

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