从Java中的字符串创建新对象

问题描述 投票:63回答:6

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

String className = "Class1";
//pseudocode follows
Object xyz = new className(param1, param2);

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

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

java
6个回答
111
投票

这是你想要做的:

String className = "Class1";
Object xyz = Class.forName(className).newInstance();

请注意,newInstance方法不允许使用参数化构造函数。 (见qazxsw poi)

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

Class.newInstance documentation

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


13
投票

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

考虑我有一个班级:

Constructor.newInstance documentation

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

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

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


2
投票

这应该工作:

com.crossedstreams.thingy.Foo@20cf2c80

从那里你可以演员到一个已知的类型。


2
投票

在JDK7中,这对我来说更干净一些,而上面的答案比从新手角度看起来要困难得多:(假设你已经将'className'声明为作为方法参数传递的String变量或者在使用此代码的方法的早期):

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

从这一点开始,您可以使用动态命名类中的属性/方法,就像您希望能够使用它们一样:

Class<?> panel = Class.forName( className );
JPanel newScreen = (JPanel) panel.newInstance();

当我尝试将.add()新的'Object'类型对象添加到框架时,上面其他答案中的示例导致错误。这里显示的技术给了我一个可用的对象,上面只有那两行代码。

不完全确定为什么 - 我自己就是Java新手。


0
投票

另一个:

JFrame frame = new JFrame(); // <<< Just so no-one gets lost here
frame.getContentPane().removeAll();
frame.getContentPane().add( newScreen );
frame.validate();
frame.repaint();

0
投票

使用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); } } 对象获取class实例的示例程序。

String

输出: -

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");
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.