[ Java ] – Create objects by reflection

Simple example for you start understand how to create an objects by reflection :

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 empty object
    public <E> E getObject(String keyClass) throws Exception {
        return (E) getClass(keyClass).newInstance();
    }

}

The example how to use this :

@Test
public void testClassMap(){
    ClassMap classMap = new ClassMap();
    Map<String, String> myMap = new HashMap<String, String>();
    myMap.put("ArrayList","java.util.ArrayList");
    classMap.setMap(myMap);
    // create new instance 
    try {
        // We used generics for don't need to do  the Cast here
        ArrayList<?> myObject = classMap.getObject("ArrayList");
    }catch (Exception r){
        System.out.println(r);
    }
}

 

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