-
Notifications
You must be signed in to change notification settings - Fork 18
type_instance
Green Luo edited this page Jan 15, 2016
·
4 revisions
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
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);
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);