Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a Class from a String

I want to instantiate a class by the value of a String. I found several tutorials that show several methods for doing this. The class MUST inherit from a certain interface, ImplementMe which has a special method called runMe(). So here's what I tried:

ImplmentMe a =
   (ImplementMe) ImplementMe.class
                   .getClassLoader()
                   .loadClass("my.package.IImplementedYou")
                   .newInstance();
a.runMe();

It works, but it's so ugly. I at least expected not needing a cast. Please tell me there is a better way.

like image 854
User1 Avatar asked Feb 01 '11 16:02

User1


People also ask

How do you load classes with class names?

Load class with forName() method in Java The class object associated with the class with the given string name can be returned with the method java. lang. Class. forName(String name, boolean initialize, ClassLoader loader), using the class loader that is used to load the class.

Is it possible to load a class by two ClassLoader?

A class is always identified using its fully qualified name (package. classname). So when a class is loaded into JVM, you have an entry as (package, classname, classloader). Therefore the same class can be loaded twice by two different ClassLoader instances.


2 Answers

No, there is no better way (by design). You are not supposed to do this, Java is designed as a type-safe language. However, I can understand that you sometimes need to do things like this, and for that purposes you can create a library function like this:

public <T> T instantiate(final String className, final Class<T> type){     try{         return type.cast(Class.forName(className).newInstance());     } catch(InstantiationException           | IllegalAccessException           | ClassNotFoundException e){         throw new IllegalStateException(e);     } } 

Now your client code can at least call this method without casting:

MyInterface thingy =     instantiate("com.foo.bar.MyInterfaceImpl", MyInterface.class); 
like image 164
Sean Patrick Floyd Avatar answered Sep 22 '22 03:09

Sean Patrick Floyd


Try Class.forName("my.package.IImplementedYou").

like image 25
kprevas Avatar answered Sep 21 '22 03:09

kprevas