[Java] – Reflection : Create a object using a constructor with arguments

With reflection you can create a object using a constructor with arguments. Bellow is the code for you can check and understand how it works :

First I created a class and an interface class to do this example :

Interface :

public interface InterfaceTest {
}

Class: 

public class MyClassTest implements InterfaceTest{

    private String A;
    private String B;
    private String C;
 
    // Look : Now we don't have more a constructor without params. 
    public MyClassTest(String a, String b, String c) {
        A = a;
        B = b;
        C = c;
    }

    public String getA() {
        return A;
    }

    public void setA(String a) {
        A = a;
    }

    public String getB() {
        return B;
    }

    public void setB(String b) {
        B = b;
    }

    public String getC() {
        return C;
    }

    public void setC(String c) {
        C = c;
    }

    // This implementation is to print all values  
    // when we write System.out.println() setting the object like param.
    // If you don't know always when we print a object, the method
    // that is called is the toString() of this object. 
    @Override
    public String toString() {
        return "MyClassTest{" +
                "A='" + A + '\'' +
                ", B='" + B + '\'' +
                ", C='" + C + '\'' +
                '}';
    }
}

Here you will see the same classMap that I used in the older posts. Also, now we have a new method implemented. In this method we will receive the constructor params.

public class ClassMap{
    private Map<String,String> map;

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    // Here we do the loading of the class and return
    public Class getClass(String keyClass) throws Exception{
        String v = map.get(keyClass);
        if(v != null){
            return Class.forName(v);
        }else{
            throw new RuntimeException("Not found with this key");
        }
    }

    // To create new instance of a object with values
    public <E> E getObjectWithParams(String keyClass, Object... params) throws Exception {
        Class<E> myClassImplementation = getClass(keyClass);
        Class<?>[] constructorTypes = new Class<?>[params.length];
        // Get the types of params
        for(int i=0; i < constructorTypes.length; i++ ){
            constructorTypes[i] = params[i].getClass();
        }
        // Create the constructor by quantity and types of params
        Constructor<?> constructor = myClassImplementation.getConstructor(constructorTypes);
        return (E) constructor.newInstance(params);
    }

}

Calling this code :

@Test
public void testClassMap(){
    ClassMap classMap = new ClassMap();
    Map<String, String> myMap = new HashMap<String, String>();
    myMap.put("InterfaceTest","MyClassTest");
    classMap.setMap(myMap);
    try {
        String[] values = {"A","B","C"}; // The values for the constructor 
        MyClassTest myOjectWithValues = classMap.getObjectWithParams("InterfaceTest", values);
        System.out.println(myOjectWithValues);
    }catch (Exception r){
        System.out.println(r);
    }
}

Result / Console :

Screen Shot 2016-06-06 at 9.43.31 AM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s