有没有办法在Java中按名称实例化一个类?

时间:2022-06-30 12:45:33

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.

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

8 个解决方案

#1


194  

Two ways:

两种方式:

Method 1 - only for classes having a no-arg constructor

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).

如果你的类有一个no-arg构造函数,你可以使用Class.forName()获取一个Class对象,并使用newInstance()方法创建一个实例(但要注意这个方法通常被认为是邪恶的,因为它可以击败Java的已检查异常)。

For example:

例如:

Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.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:

如果类没有任何no-arg构造函数,那么另一种更安全的方法是查询类对象以获取其Constructor对象并在此对象上调用newInstance()方法:

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:

这两种方法都称为反射。您通常必须捕获​​可能发生的各种异常,包括以下内容:

  • the JVM can't find or can't load your class
  • JVM无法找到或无法加载您的类
  • 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
  • 已安装安全管理器并阻止反射发生

#2


12  

MyClass myInstance = (MyClass) Class.forName("MyClass").newInstance();

#3


3  

use Class.forName("String name of class").newInstance();

使用Class.forName(“类的字符串名称”)。newInstance();

Class.forName("A").newInstance();

This will cause class named A initialized.

这将导致名为A的类初始化。

#4


2  

To make it easier to get the fully qualified name of a class in order to create an instance using Class.forName(...), one could use the Class.getName() method. Something like:

为了更容易获取类的完全限定名称以便使用Class.forName(...)创建实例,可以使用Class.getName()方法。就像是:

class ObjectMaker {
    // Constructor, fields, initialization, etc...
    public Object makeObject(Class<?> clazz) {
        Object o = null;

        try {
            o = Class.forName(clazz.getName()).newInstance();
        } catch (ClassNotFoundException e) {
            // There may be other exceptions to throw here, 
            // but I'm writing this from memory.
            e.printStackTrace();
        }

        return o;
    }
}

Then you can cast the object you get back to whatever class you pass to makeObject(...):

然后你可以将你得到的对象转换为你传递给makeObject(...)的任何类:

Data d = (Data) objectMaker.makeObject(Data.class);

#5


1  

Use java reflection

使用java反射

Creating New Objects There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction). So the nearest equivalent to the previous example is to say:

创建新对象没有与构造函数的方法调用等效,因为调用构造函数等同于创建新对象(最精确的是,创建新对象涉及内存分配和对象构造)。所以与上一个例子最接近的等价是:

import java.lang.reflect.*;

   public class constructor2 {
      public constructor2()
      {
      }

      public constructor2(int a, int b)
      {
         System.out.println(
           "a = " + a + " b = " + b);
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("constructor2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Constructor ct 
              = cls.getConstructor(partypes);
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj = ct.newInstance(arglist);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

which finds a constructor that handles the specified parameter types and invokes it, to create a new instance of the object. The value of this approach is that it's purely dynamic, with constructor lookup and invocation at execution time, rather than at compilation time.

它找到一个处理指定参数类型并调用它的构造函数,以创建该对象的新实例。这种方法的价值在于它纯粹是动态的,在执行时使用构造函数查找和调用,而不是在编译时。

#6


1  

Class.forName("ClassName") will solve your purpose.

Class.forName(“ClassName”)将解决您的目的。

Class class1 = Class.forName(ClassName);
Object object1 = class1.newInstance();

#7


0  

String str = (String)Class.forName("java.lang.String").newInstance();

#8


0  

something like this should work...

这样的事情应该有效......

String name = "Test2";//Name of the class
        Class myClass = Class.forName(name);
        Object o = myClass.newInstance();

#1


194  

Two ways:

两种方式:

Method 1 - only for classes having a no-arg constructor

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).

如果你的类有一个no-arg构造函数,你可以使用Class.forName()获取一个Class对象,并使用newInstance()方法创建一个实例(但要注意这个方法通常被认为是邪恶的,因为它可以击败Java的已检查异常)。

For example:

例如:

Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.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:

如果类没有任何no-arg构造函数,那么另一种更安全的方法是查询类对象以获取其Constructor对象并在此对象上调用newInstance()方法:

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:

这两种方法都称为反射。您通常必须捕获​​可能发生的各种异常,包括以下内容:

  • the JVM can't find or can't load your class
  • JVM无法找到或无法加载您的类
  • 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
  • 已安装安全管理器并阻止反射发生

#2


12  

MyClass myInstance = (MyClass) Class.forName("MyClass").newInstance();

#3


3  

use Class.forName("String name of class").newInstance();

使用Class.forName(“类的字符串名称”)。newInstance();

Class.forName("A").newInstance();

This will cause class named A initialized.

这将导致名为A的类初始化。

#4


2  

To make it easier to get the fully qualified name of a class in order to create an instance using Class.forName(...), one could use the Class.getName() method. Something like:

为了更容易获取类的完全限定名称以便使用Class.forName(...)创建实例,可以使用Class.getName()方法。就像是:

class ObjectMaker {
    // Constructor, fields, initialization, etc...
    public Object makeObject(Class<?> clazz) {
        Object o = null;

        try {
            o = Class.forName(clazz.getName()).newInstance();
        } catch (ClassNotFoundException e) {
            // There may be other exceptions to throw here, 
            // but I'm writing this from memory.
            e.printStackTrace();
        }

        return o;
    }
}

Then you can cast the object you get back to whatever class you pass to makeObject(...):

然后你可以将你得到的对象转换为你传递给makeObject(...)的任何类:

Data d = (Data) objectMaker.makeObject(Data.class);

#5


1  

Use java reflection

使用java反射

Creating New Objects There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction). So the nearest equivalent to the previous example is to say:

创建新对象没有与构造函数的方法调用等效,因为调用构造函数等同于创建新对象(最精确的是,创建新对象涉及内存分配和对象构造)。所以与上一个例子最接近的等价是:

import java.lang.reflect.*;

   public class constructor2 {
      public constructor2()
      {
      }

      public constructor2(int a, int b)
      {
         System.out.println(
           "a = " + a + " b = " + b);
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("constructor2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Constructor ct 
              = cls.getConstructor(partypes);
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj = ct.newInstance(arglist);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

which finds a constructor that handles the specified parameter types and invokes it, to create a new instance of the object. The value of this approach is that it's purely dynamic, with constructor lookup and invocation at execution time, rather than at compilation time.

它找到一个处理指定参数类型并调用它的构造函数,以创建该对象的新实例。这种方法的价值在于它纯粹是动态的,在执行时使用构造函数查找和调用,而不是在编译时。

#6


1  

Class.forName("ClassName") will solve your purpose.

Class.forName(“ClassName”)将解决您的目的。

Class class1 = Class.forName(ClassName);
Object object1 = class1.newInstance();

#7


0  

String str = (String)Class.forName("java.lang.String").newInstance();

#8


0  

something like this should work...

这样的事情应该有效......

String name = "Test2";//Name of the class
        Class myClass = Class.forName(name);
        Object o = myClass.newInstance();