I have a method that needs a Class object which it will construct multiple times:
Class<?> clazz = MyClass.class;
register(clazz);
For some registers, I want to use anonymous classes, but for that I need a Class<?> object from it.
I would use it for registering multiple classes that are very similar, but (in this example) have a different name:
String[] nameList = { "name1", "name2" }; // and a lot more
for (final String name : nameList) {
// How would I do the next line?
// It is supposed to pass the Class<?> for an anonymous class overriding getName()
register(AnAnonymousClass {
@Override
public String getName() {
return name;
});
}
}
Is there any way of doing this, or does my system have a design flaw? If yes, how would I achieve it then? By the way, I cannot pass the name via constructor because the constructor has to have the same parameters for all classes (because it will be constructed using reflection).
getClass()method on any object. But if you're trying to set up an anonymous inner class without creating an object of that class, offhand I'm not sure Java supports this. Maybe you can define a named local class with a name and use that.name.