有没有办法在Java中按名称实例化一个类? [英] Is there a way to instantiate a class by name in Java?
问题描述
我的问题是:从字符串名称实例化一个类描述了如何在拥有名称时实例化一个类。有没有办法在Java中做到这一点?我将拥有包名和类名,我需要能够创建一个具有该特定名称的对象。
I was looking as the question : Instantiate an class from its string name which describes how to instantiate a class when having its name. Is there a way to do it in Java? I will have the package name and class name and I need to be able to create an object having that particular name.
推荐答案
两个方式:
如果您的类没有-arg构造函数,您可以使用 Class.forName()
获取 Class
对象并使用 newInstance()
创建实例的方法(虽然要注意这种方法通常是被认为是邪恶的,因为它可以击败Java的已检查异常)。
If your class has a no-arg constructor, you can get a Class
object using Class.forName()
and use the newInstance()
method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).
例如:
Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.newInstance();
方法2
另一种更安全的方法如果类没有任何no-arg构造函数,它也可以查询你的类对象以获取它的构造函数
对象并调用 newInstance( )
此对象的方法:
Method 2
An alternative safer approach which also works if the class doesn't have any no-arg constructors is to query your class object to get its Constructor
object and call a newInstance()
method on this object:
Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);
这两种方法都称为反射。您通常必须捕获可能发生的各种异常,包括:
Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:
- JVM无法找到或无法加载你的类
- 你试图实例化的类没有正确的构造函数
- 构造函数本身抛出异常
- 您尝试调用的构造函数不公开
- 已安装安全管理器并阻止反射发生
- the JVM can't find or can't load your class
- the class you're trying to instantiate doesn't have the right sort of constructors
- the constructor itself threw an exception
- the constructor you're trying to invoke isn't public
- a security manager has been installed and is preventing reflection from occurring
这篇关于有没有办法在Java中按名称实例化一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!