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.
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.
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.
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);
Try Class.forName("my.package.IImplementedYou")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With