在Java中从字符串创建新对象
有没有一种方法可以从Java中的字符串变量创建一个新类在Java中从字符串创建新对象,java,Java,有没有一种方法可以从Java中的字符串变量创建一个新类 String className = "Class1"; //pseudocode follows Object xyz = new className(param1, param2); 此外,如果可能,结果对象是否必须是object类型 可能有更好的方法,但我希望能够从XML文件中检索值,然后实例化以这些字符串命名的类。这些类中的每一个都实现了相同的接口,并且都是从相同的父类派生的,因此我可以调用该类中的特定方法。是的,您可以使用反射、
String className = "Class1";
//pseudocode follows
Object xyz = new className(param1, param2);
此外,如果可能,结果对象是否必须是object类型
可能有更好的方法,但我希望能够从XML文件中检索值,然后实例化以这些字符串命名的类。这些类中的每一个都实现了相同的接口,并且都是从相同的父类派生的,因此我可以调用该类中的特定方法。是的,您可以使用反射、class.forName(name)在给定字符串名的类路径上加载一个类,获取构造函数并调用它。我给你举个例子 假设我有一门课:
com.crossedstreams.thingy.Foo
其中有一个带签名的构造函数:
Foo(String a, String b);
我将根据以下两个事实实例化该类:
// 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);
输出:
com.crossedstreams.thingy.Foo@20cf2c80
有大量的资源详细介绍了这一点,您应该知道,您引入了一个编译器无法为您检查的依赖项-如果您拼写错误类名或任何内容,它将在运行时失败。
此外,在这个过程中可能会抛出许多不同类型的异常。这是一项非常强大的技术。这就是您想要做的:
String className = "Class1";
Object xyz = Class.forName(className).newInstance();
请注意,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);
请参见这应该可以:
import java.lang.reflect.*;
FirstArgType arg1;
SecondArgType arg2;
Class cl = Class.forName("TheClassName");
Constructor con = cl.getConstructor(FirstArgType.class, SecondArgType.class);
Object obj = con.newInstance(arg1, arg2);
从那里您可以强制转换为已知类型 另一个:
import java.lang.reflect.Constructor;
public class Test {
public Test(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return this.name;
}
private String name;
public static void main(String[] args) throws Exception {
String className = "Test";
Class clazz = Class.forName(className);
Constructor tc = clazz.getConstructor(String.class);
Object t = tc.newInstance("John");
System.out.println(t);
}
}
这对我在JDK7中的工作更为清晰,而上面的答案让事情变得比新手的角度更为困难:(假设您已将“className”声明为作为方法参数传递的字符串变量,或者在使用此代码的方法的早期声明为):
Class panel=Class.forName(className);
JPanel newScreen=(JPanel)panel.newInstance();
从这一点出发,您可以完全按照预期的方式使用动态命名类中的属性/方法:
JFrame frame = new JFrame(); // <<< Just so no-one gets lost here
frame.getContentPane().removeAll();
frame.getContentPane().add( newScreen );
frame.validate();
frame.repaint();
JFrame=newjframe();//使用字符串
对象获取类
实例的示例程序。
输出:-
你可以用getConstructor来构造参数化的构造函数。你说得对,我不知道。我将编辑我的答案以反映更好的方式。我认为使用GetConstructor比使用init方法更好。因为使用构造函数允许分配最终字段。将第7行更改为:constructor con=cl.getConstructor(新类[]{Param1Type.Class,Param2Type.Class});如果您使用:Object xyz=Class.forName(className).newInstance(),您也应该知道;您将以静默方式将选中的异常转换为未选中的异常。这个答案中的更多细节:问题:既然我们已经创建了Foo
的对象,那么我们如何使用该对象调用Foo
的公共函数呢?我们如何将其转换为Foo
引用?您可以像转换任何对象一样进行转换<代码>(Foo)o
或Foo.class.cast(o)
。不过,您可能不想这样做,因为如果您知道实现类是什么,那么进行此操作是毫无意义的—您可以直接导入它!您实际要做的是将其转换为实现必须实现的接口,您已经导入了该接口。
JFrame frame = new JFrame(); // <<< Just so no-one gets lost here
frame.getContentPane().removeAll();
frame.getContentPane().add( newScreen );
frame.validate();
frame.repaint();
public class GetStudentObjectFromString
{
public static void main (String[] args) throws java.lang.Exception
{
String className = "Student"; //Passed the Class Name in String Object.
//A Object of Student will made by Invoking its Default Constructor.
Object o = Class.forName(className).newInstance();
if(o instanceof Student) // Verify Your Instance that Is it Student Type or not?
System.out.println("Hurrey You Got The Instance of " + className);
}
}
class Student{
public Student(){
System.out.println("Constructor Invoked");
}
}
Constructor Invoked
Hurrey You Got The Instance of Student