使用类名和调用构造函数创建实例。

时间:2020-12-22 14:30:11

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构造函数的一个参数。

10 个解决方案

#1


418  

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, i.e. 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. forname(“foo.Outer$嵌套”)。

#2


77  

You can use Class.forName() to get a Class object of the desired class.

可以使用Class. forname()获取所需类的类对象。

Then use getConstructor() to find the desired Constructor object.

然后使用getConstructor()查找所需的构造函数对象。

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

#3


70  

You can use reflections

您可以使用反射

return Class.forName(className).getConstructor(String.class).newInstance(arg);

#4


11  

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

#5


6  

when using (i.e.) getConstructor(String.lang) the constructor has to be declared public. Otherwise a NoSuchMethodException is thrown.

当使用(例如)getConstructor(String.lang)时,构造函数必须声明为public。否则会抛出nosuchmethdexception。

if you want to access a non-public constructor you have to use instead (i.e.) getDeclaredConstructor(String.lang).

如果您想访问一个非公共构造函数,您必须使用(例如)getDeclaredConstructor(String.lang)。

#6


3  

You want to be using java.lang.reflect.Constructor.newInstance(Object...)

您希望使用java.lang.reflec . constructor.newinstance(对象…)

#7


2  

Very Simple way to create an object in Java using Class<?> with constructor argument(s) passing:

使用类

Case 1:- Here, is a small code in this Main class:

案例1:-这里是这个主要类中的一个小代码:

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:

这是基类结构:

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. 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:

案例2:-您,可以对具有多个参数和复制构造函数的构造函数使用类似的代码。例如,将3个参数作为参数传递给基本构造函数,将需要在类中创建构造函数,并在上面的代码更改如下:

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:

这里的基类应该是这样的

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.

注意:-不要忘记处理代码中需要处理的各种异常。

#8


1  

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.

通过调用第一个constractor,然后在创建的对象中调用第一个方法,可以立即创建对象。

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

#9


1  

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.

这只适用于使用私有构造函数实现单例模式的类。

#10


-1  

Another helpful answer. How do I use getConstructor(params).newInstance(args)?

另一个有用的答案。如何使用getConstructor .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);

#1


418  

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, i.e. 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. forname(“foo.Outer$嵌套”)。

#2


77  

You can use Class.forName() to get a Class object of the desired class.

可以使用Class. forname()获取所需类的类对象。

Then use getConstructor() to find the desired Constructor object.

然后使用getConstructor()查找所需的构造函数对象。

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

#3


70  

You can use reflections

您可以使用反射

return Class.forName(className).getConstructor(String.class).newInstance(arg);

#4


11  

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

#5


6  

when using (i.e.) getConstructor(String.lang) the constructor has to be declared public. Otherwise a NoSuchMethodException is thrown.

当使用(例如)getConstructor(String.lang)时,构造函数必须声明为public。否则会抛出nosuchmethdexception。

if you want to access a non-public constructor you have to use instead (i.e.) getDeclaredConstructor(String.lang).

如果您想访问一个非公共构造函数,您必须使用(例如)getDeclaredConstructor(String.lang)。

#6


3  

You want to be using java.lang.reflect.Constructor.newInstance(Object...)

您希望使用java.lang.reflec . constructor.newinstance(对象…)

#7


2  

Very Simple way to create an object in Java using Class<?> with constructor argument(s) passing:

使用类

Case 1:- Here, is a small code in this Main class:

案例1:-这里是这个主要类中的一个小代码:

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:

这是基类结构:

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. 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:

案例2:-您,可以对具有多个参数和复制构造函数的构造函数使用类似的代码。例如,将3个参数作为参数传递给基本构造函数,将需要在类中创建构造函数,并在上面的代码更改如下:

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:

这里的基类应该是这样的

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.

注意:-不要忘记处理代码中需要处理的各种异常。

#8


1  

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.

通过调用第一个constractor,然后在创建的对象中调用第一个方法,可以立即创建对象。

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

#9


1  

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.

这只适用于使用私有构造函数实现单例模式的类。

#10


-1  

Another helpful answer. How do I use getConstructor(params).newInstance(args)?

另一个有用的答案。如何使用getConstructor .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);