从 Java 中的字符串创建新对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1268817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create new object from a string in Java
提问by jW.
Is there a way to create a new class from a String variable in Java?
有没有办法从 Java 中的 String 变量创建一个新类?
String className = "Class1";
//pseudocode follows
Object xyz = new className(param1, param2);
Also, if possible does the resulting object have to be of type Object?
另外,如果可能的话,结果对象必须是 Object 类型吗?
There may be a better way, but I want to be able to retrieve values from an XML file, then instantiate the classes named after those strings. Each of these classes implement the same interface and are derived from the same parent class, so I would then be able to call a particular method in that class.
可能有更好的方法,但我希望能够从 XML 文件中检索值,然后实例化以这些字符串命名的类。这些类中的每一个都实现相同的接口并派生自相同的父类,因此我将能够调用该类中的特定方法。
采纳答案by Dawie Strauss
This is what you want to do:
这是你想要做的:
String className = "Class1";
Object xyz = Class.forName(className).newInstance();
Note that the newInstance method does not allow a parametrized constructor to be used. (See Class.newInstance documentation)
请注意, newInstance 方法不允许使用参数化构造函数。(参见Class.newInstance 文档)
If you do need to use a parametrized constructor, this is what you need to do:
如果确实需要使用参数化构造函数,则需要执行以下操作:
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);
回答by brabster
Yes, you can load a class on your classpath given the String name using reflection, using Class.forName(name), grabbing the constructor and invoking it. I'll do you an example.
是的,您可以使用反射,使用 Class.forName(name),获取构造函数并调用它,在给定字符串名称的类路径上加载类。我给你举个例子。
Consider I have a class:
考虑我有一堂课:
com.crossedstreams.thingy.Foo
Which has a constructor with signature:
其中有一个带有签名的构造函数:
Foo(String a, String b);
I would instantiate the class based on these two facts as follows:
我将根据这两个事实实例化该类,如下所示:
// 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);
Output:
输出:
com.crossedstreams.thingy.Foo@20cf2c80
There's plenty of resources out there which go into more detail about this, and you should be aware that you're introducing a dependency that the compiler can't check for you - if you misspell the class name or anything, it will fail at runtime. Also, there's quite a few different types of Exception that might be throws during this process. It's a very powerful technique though.
有很多资源可以更详细地介绍这一点,您应该意识到您引入了编译器无法为您检查的依赖项 - 如果您拼错了类名或其他任何内容,它将在运行时失败. 此外,在此过程中可能会抛出多种不同类型的异常。不过这是一个非常强大的技术。
回答by CodeGoat
This should work:
这应该有效:
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);
From there you can cast to a known type.
从那里您可以转换为已知类型。
回答by rodrigoap
Another one:
另一个:
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);
}
}
回答by Ragdata
This worked a little more cleanly for me in JDK7, while the answers above made things a bit more difficult than they needed to be from a newbie perspective: (assumes you've declared 'className' as a String variable passed as a method parameter or earlier in the method using this code):
这在 JDK7 中对我来说更干净一些,而上面的答案使事情变得比从新手的角度更难:(假设您已将“className”声明为作为方法参数传递的字符串变量或在使用此代码的方法的早期):
Class<?> panel = Class.forName( className );
JPanel newScreen = (JPanel) panel.newInstance();
From this point you can use properties / methods from your dynamically-named class exactly as you would expect to be able to use them:
从这一点开始,您可以完全按照您期望的方式使用动态命名类中的属性/方法:
JFrame frame = new JFrame(); // <<< Just so no-one gets lost here
frame.getContentPane().removeAll();
frame.getContentPane().add( newScreen );
frame.validate();
frame.repaint();
The examples in other answers above resulted in errors when I tried to .add() the new 'Object' type object to the frame. The technique shown here gave me a usable object with just those 2 lines of code above.
当我尝试将新的“对象”类型对象添加到框架时,上面其他答案中的示例导致错误。这里展示的技术给了我一个可用的对象,只有上面的那两行代码。
Not exactly certain why that was - I'm a Java newbie myself.
不完全确定这是为什么 - 我自己是 Java 新手。
回答by Vikrant Kashyap
A Sample Program to Get Instance of a class
using String
Object.
获取class
usingString
对象实例的示例程序。
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");
}
}
Output :-
输出 :-
Constructor Invoked Hurrey You Got The Instance of Student
Constructor Invoked Hurrey You Got The Instance of Student