从Java中的Variable创建新类

jW.*_*jW. 65 java

有没有办法从Java中的String变量创建一个新类?

String className = "Class1";
//pseudocode follows
Object xyz = new className(param1, param2);
Run Code Online (Sandbox Code Playgroud)

另外,如果可能,结果对象必须是Object类型?

可能有更好的方法,但我希望能够从XML文件中检索值,然后创建以这些字符串命名的类.每个类都实现相同的接口,并从同一个父类派生,因此我可以调用该类中的特定方法.

Daw*_*uss 116

这是你想要做的:

String className = "Class1";
Object xyz = Class.forName(className).newInstance();
Run Code Online (Sandbox Code Playgroud)

请注意,newInstance方法不允许使用参数化构造函数.(参见Class.newInstance文档)

如果确实需要使用参数化构造函数,那么您需要执行以下操作:

import java.lang.reflect.*;

Param1Type param1;
Param2Type param2;
String className = "Class1";
Class cl = Class.forName(className);
Constructor con = cl.getConstructor(Param1Type.class, Param2Type.class);
Object xyz = con.newInstance(param1, param2);
Run Code Online (Sandbox Code Playgroud)

请参阅Constructor.newInstance文档

  • 您可以将getConstructor用于参数化构造函数. (6认同)

bra*_*ter 14

是的,你可以在类路径上加载一个类,给定使用反射的String名称,使用Class.forName(name),抓取构造函数并调用它.我会给你一个例子.

考虑我有一个班级:

com.crossedstreams.thingy.Foo
Run Code Online (Sandbox Code Playgroud)

其中有一个带签名的构造函数:

Foo(String a, String b);
Run Code Online (Sandbox Code Playgroud)

我将根据以下两个事实实例化该类:

// Load the Class. Must use fully qualified name here!
Class clazz = Class.forName("com.crossedstreams.thingy.Foo");

// I need an array as follows to describe the signature
Class[] parameters = new Class[] {String.class, String.class};

// Now I can get a reference to the right constructor
Constructor constructor = clazz.getConstructor(parameters);

// And I can use that Constructor to instantiate the class
Object o = constructor.newInstance(new Object[] {"one", "two"});

// To prove it's really there...
System.out.println(o);
Run Code Online (Sandbox Code Playgroud)

输出:

com.crossedstreams.thingy.Foo@20cf2c80
Run Code Online (Sandbox Code Playgroud)

有大量的资源可以更详细地了解这一点,你应该知道你引入了一个编译器无法检查的依赖项 - 如果你拼错了类名或任何东西,它将在运行时失败.此外,在此过程中可能会抛出相当多的不同类型的异常.但这是一种非常强大的技术.