开发者

how to use reflection package to create an object from a classpath

开发者 https://www.devze.com 2023-01-30 14:41 出处:网络
I want to create an object I know only its classpath Any help w开发者_运维问答ill be appreciated.If you have the full qualified classname in a String, use Class#forName() and Class#newInstance().

I want to create an object I know only its classpath Any help w开发者_运维问答ill be appreciated.


If you have the full qualified classname in a String, use Class#forName() and Class#newInstance().

Object o = Class.forName("com.example.Foo").newInstance();

This however requires the class to be already present in the classpath and have a (implicit) default constructor.

If it is not, and you have the class' location in an URL, then use URLClassLoader and pass it to another Class#forName() method which accepts it as an argument.

URL url = getItSomehow();
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { url });
Object o = Class.forName("com.example.Foo", true, classLoader).newInstance();

Or, if you have it in a File instead, then convert it to URL first:

File file = getItSomehow();
URL url = file.toURI().toURL();
// Continue with URLClassLoader.


Did you mean this ?

Class c = Class.forName("java.lang.String");
0

精彩评论

暂无评论...
验证码 换一张
取 消