I have some legacy code that looks like:
Set<Class<? extends Foo>> classes = reflections.getSubTypesOf(Foo.class);
for (Class<? extends Foo> cl : classes) {
Foo<?, ?> foo = cl.newInstance();
// use foo
}
I'd like to add another interface:
interface NewFoo extends Foo {...}
But then it tries to call newInstance on NewFoo. For now my solution is this:
try {
Foo<?, ?> foo = cl.newInstance();
// use foo
} catch (InstantiationException ignore) {
}
but I wonder if there's a better way? Can I differentiate between an interface and a class when I have a Class object in my hand?
Aucun commentaire:
Enregistrer un commentaire