Skip to content
Green Luo edited this page Jan 15, 2016 · 4 revisions

Why tools for Class and instance?

In simple words: I don't like checked exception and I see it as a liability to Java programming. The utilities for Class/Instance creation are built to remove the barrier

Loading class and creating instances

Old way

Class<MyInterface> clazz;
try {
    clazz = (Class<MyInterface>)Class.forName(cname);
} catch (ClassNotFoundException e) {
    // now what to do except throwing it out?
    throw new RuntimeException(e);
}
MyInterface impl;
try {
    impl = clazz.newInstance();
} catch (InstantiationException e) {
    throw new RuntimeException(e);
} catch (IllegalAccessException e) {
    throw new RuntimeException(e);
}

New way

Class<MyInterface> clazz = $.classForName(cname);
MyInterface impl = $.newInstance(clazz);

Constructor with parameters

Old way

Class<MyInterface> clazz;
try {
    clazz = (Class<MyInterface>)Class.forName(cname);
} catch (ClassNotFoundException e) {
    // now what to do except throwing it out?
    throw new RuntimeException(e);
}
MyInterface impl;
try {
    Constructor<MyInterface> constructor = clazz.getConstructor(String.class, Integer.class);
    impl = constructor.newInstance("name", 5);
} catch (NoSuchMethodException e) {
    throw new RuntimeException(e);
} catch (InstantiationException e) {
    throw new RuntimeException(e);
} catch (InvocationTargetException e) {
    throw new RuntimeException(e.getTargetException());
} catch (IllegalAccessException e) {
    throw new RuntimeException(e);
}

New way

Class<FooBase> clazz = $.classForName(cname);
FooBase foo = $.newInstance(clazz, "name", 5);