有没有办法在Java中按名称实例化一个类? [英] Is there a way to instantiate a class by name in Java?

查看:42
本文介绍了有没有办法在Java中按名称实例化一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看问题:从字符串名称实例化一个类 描述了如何在拥有名称时实例化类.有没有办法在Java中做到这一点?我将获得包名和类名,并且我需要能够创建具有该特定名称的对象.

I was looking as the question : Instantiate a 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.

推荐答案

两种方式:

如果您的类具有无参数构造函数,您可以使用 Class.forName() 获取 Class 对象并使用 newInstance()code> 方法来创建一个实例(但请注意,此方法通常被认为是邪恶的,因为它可以打败 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();

方法二

如果类没有任何无参数构造函数,另一种更安全的方法也适用,即查询您的类对象以获取其 Constructor 对象并调用 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);

这两种方法都被称为reflection.您通常必须捕获​​可能发生的各种异常,包括:

Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:

  • JVM 找不到或无法加载您的类
  • 您尝试实例化的类没有正确类型的构造函数
  • 构造函数本身抛出异常
  • 您尝试调用的构造函数不是公开的
  • 已安装安全管理器并防止发生反射

这篇关于有没有办法在Java中按名称实例化一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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