Reputation: 2264
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).
Upvotes: 0
Views: 1583
Reputation: 3304
I believe that Peter Lawrey is right in that you are not creating different classes in your loop, only instances.
Are all the classes that you need to "register" your own? If so, you could create an interface for them all that contains a copy method. Instead of registering classes and using reflection to create instances, you register an original object and copy that, like so:
// Interface with methods that all these classes have in common
interface MyClassInterface {
MyClassInterface copy();
String getName();
}
@Test
public void testMyClasses() {
List<String> names = new ArrayList<>();
// Example list of names
names.add("adam");
names.add("ben");
names.add("carl");
List<MyClassInterface> objects = new ArrayList<>();
// Define specialized class with special implementation of getName
class MyClassWithName implements MyClassInterface {
private String name;
public MyClassWithName(String name) {
this.name = name;
}
@Override
public MyClassInterface copy() {
return new MyClassWithName(name);
}
@Override
public String getName() {
return name;
}
}
for (final String name: names) {
// "register" object
objects.add(new MyClassWithName(name));
}
for (MyClassInterface object: objects) {
System.out.println("original name " + object.getName());
// Construct copies as needed
MyClassInterface object2 = object.copy();
System.out.println("copy name " + object2.getName());
}
}
Upvotes: 2