[英]Creating an instance using the class name and calling constructor
Is there a way to create an instance of a particular class given the class name (dynamic) and pass parameters to its constructor.有没有办法在给定类名(动态)的情况下创建特定类的实例并将参数传递给其构造函数。
Something like:就像是:
Object object = createInstance("mypackage.MyClass","MyAttributeValue");
Where "MyAttributeValue"
is an argument to the constructor of MyClass
.其中
"MyAttributeValue"
是MyClass
构造函数的参数。
Yes, something like:是的,类似于:
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });
That will only work for a single string parameter of course, but you can modify it pretty easily.这当然只适用于单个字符串参数,但您可以很容易地修改它。
Note that the class name has to be a fully-qualified one, ie including the namespace.请注意,类名必须是完全限定的,即包括命名空间。 For nested classes, you need to use a dollar (as that's what the compiler uses).
对于嵌套类,您需要使用美元(因为这是编译器使用的)。 For example:
例如:
package foo;
public class Outer
{
public static class Nested {}
}
To obtain the Class
object for that, you'd need Class.forName("foo.Outer$Nested")
.要为此获取
Class
对象,您需要Class.forName("foo.Outer$Nested")
。
You can use Class.forName()
to get a Class
object of the desired class.您可以使用
Class.forName()
获取所需类的Class
对象。
Then use getConstructor()
to find the desired Constructor
object.然后使用
getConstructor()
找到所需的Constructor
对象。
Finally, call newInstance()
on that object to get your new instance.最后,对该对象调用
newInstance()
以获取新实例。
Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("MyAttributeValue");
您可以使用反射
return Class.forName(className).getConstructor(String.class).newInstance(arg);
If class has only one empty constructor (like Activity or Fragment etc, android classes):如果类只有一个空构造函数(如 Activity 或 Fragment 等,android 类):
Class<?> myClass = Class.forName("com.example.MyClass");
Constructor<?> constructor = myClass.getConstructors()[0];
when using (ie) getConstructor(String.lang)
the constructor has to be declared public.使用(即)
getConstructor(String.lang)
,必须将构造函数声明为public。 Otherwise a NoSuchMethodException
is thrown.否则
NoSuchMethodException
。
if you want to access a non-public constructor you have to use instead (ie) getDeclaredConstructor(String.lang)
.如果要访问非公共构造函数,则必须改用(即)
getDeclaredConstructor(String.lang)
。
Very Simple way to create an object in Java using Class<?>
with constructor argument(s) passing:使用
Class<?>
和构造函数参数在 Java 中创建对象的非常简单的方法:
Case 1:- Here, is a small code in this Main
class:案例 1:-这是
Main
类中的一小段代码:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Main {
public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Get class name as string.
String myClassName = Base.class.getName();
// Create class of type Base.
Class<?> myClass = Class.forName(myClassName);
// Create constructor call with argument types.
Constructor<?> ctr = myClass.getConstructor(String.class);
// Finally create object of type Base and pass data to constructor.
String arg1 = "My User Data";
Object object = ctr.newInstance(new Object[] { arg1 });
// Type-cast and access the data from class Base.
Base base = (Base)object;
System.out.println(base.data);
}
}
And, here is the Base
class structure:而且,这是
Base
类结构:
public class Base {
public String data = null;
public Base()
{
data = "default";
System.out.println("Base()");
}
public Base(String arg1) {
data = arg1;
System.out.println("Base("+arg1+")");
}
}
Case 2:- You, can code similarly for constructor with multiple argument and copy constructor.情况 2:-您可以为具有多个参数和复制构造函数的构造函数编写类似的代码。 For example, passing 3 arguments as parameter to the
Base
constructor will need the constructor to be created in class and a code change in above as:例如,将 3 个参数作为参数传递给
Base
构造函数将需要在类中创建构造函数,并且上面的代码更改为:
Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" });
And here the Base class should somehow look like:这里的 Base 类应该看起来像:
public class Base {
public Base(String a, String b, String c){
// This constructor need to be created in this case.
}
}
Note:- Don't forget to handle the various exceptions which need to be handled in the code.注意:-不要忘记处理需要在代码中处理的各种异常。
If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.如果有人正在寻找一种方法来创建类的实例,尽管类遵循单例模式,这里有一种方法可以做到。
// Get Class instance
Class<?> clazz = Class.forName("myPackage.MyClass");
// Get the private constructor.
Constructor<?> cons = clazz.getDeclaredConstructor();
// Since it is private, make it accessible.
cons.setAccessible(true);
// Create new object.
Object obj = cons.newInstance();
This only works for classes that implement singleton pattern using a private constructor.这仅适用于使用私有构造函数实现单例模式的类。
Another helpful answer.另一个有用的答案。 How do I use getConstructor(params).newInstance(args)?
我如何使用 getConstructor(params).newInstance(args)?
return Class.forName(**complete classname**)
.getConstructor(**here pass parameters passed in constructor**)
.newInstance(**here pass arguments**);
In my case, my class's constructor takes Webdriver as parameter, so used below code:就我而言,我的类的构造函数将 Webdriver 作为参数,因此使用以下代码:
return Class.forName("com.page.BillablePage")
.getConstructor(WebDriver.class)
.newInstance(this.driver);
You can also invoke methods inside the created object.您还可以在创建的对象中调用方法。
You can create object instant by invoking the first constractor and then invoke the first method in the created object.您可以通过调用第一个构造函数然后调用创建的对象中的第一个方法来创建对象即时。
Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> ctor = c.getConstructors()[0];
Object object=ctor.newInstance(new Object[]{"ContstractorArgs"});
c.getDeclaredMethods()[0].invoke(object,Object... MethodArgs);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.