如何使用反射包从类路径创建对象 [英] how to use reflection package to create an object from a classpath

查看:371
本文介绍了如何使用反射包从类路径创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个对象我只知道它的类路径
任何帮助都会受到赞赏。

I want to create an object I know only its classpath Any help will be appreciated.

推荐答案

如果你有一个 String 中的完全限定类名,使用 Class#forName() Class#newInstance()

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.

如果不是,并且您的班级位置在 URL ,然后使用 URLClassLoader 并将其传递给另一个 Class#forName() 方法接受它作为参数。

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.

这篇关于如何使用反射包从类路径创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆