Creating an instance using the class name and calling constructor

前端 未结 10 2353
醉话见心
醉话见心 2020-11-22 05:51

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:

Obj         


        
10条回答
  •  盖世英雄少女心
    2020-11-22 06:48

    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:

    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:

    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.

提交回复
热议问题