List of classes implementing the interface

Is there a way to implement something like

List<Class<? implements MyInterface>> ClassList = new ArrayList<Class<? implements MyInterface>>(); 

My goal is to create a hash map from this list, where the keys are the toString methods of the class (defined in MyInterface) and the values ​​are the classes themselves. The toString method of each object of this class returns the same result. That way, I could create class instances using the map, by searching for the correct strings.

Thanks for trying to help, greetings

+7
source share
2 answers
 List<Class<? implements MyInterface>> ClassList = new ArrayList<Class<? implements MyInterface>>(); 

it should be

 List<Class<? extends MyInterface>> ClassList = new ArrayList<Class<? extends MyInterface>>(); 

in the generic world there is no keyword . if you need a type parameter that implements the interface, use extends keyword to represent it.

+13
source

Since you seem to be interested in, as I explained, here is a brief implementation to verify that this can be done ...

 import java.util.ArrayList; import java.util.List; enum NumberClass { ONE("One"), TWO("Two"), THREE("Three"); private final String className; NumberClass(String name) { className = name; } String getName() { return className; } } public class Test { public static void main(String[] args) { List<NumberClass> numbers = new ArrayList<NumberClass>(); numbers.add(NumberClass.ONE); numbers.add(NumberClass.THREE); numbers.add(NumberClass.TWO); numbers.add(NumberClass.ONE); numbers.add(NumberClass.THREE); numbers.add(NumberClass.ONE); numbers.add(NumberClass.TWO); SomeNumber[] nbs = new SomeNumber[numbers.size()]; int i = 0; for (NumberClass nbC : numbers) { SomeNumber nb; try { nb = (SomeNumber) Class.forName(nbC.getName()).newInstance (); nbs[i++] = nb; } // Cleanly handle them! catch (InstantiationException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } catch (ClassNotFoundException e) { System.out.println(e); } } for (SomeNumber sn : nbs) { System.out.println(sn.getClass().getName() + " " + sn.getValue()); } } } // The following must be in their own files, of course public interface SomeNumber { int getValue(); } public class One implements SomeNumber { public int getValue() { return 1; } } public class Two implements SomeNumber { public int getValue() { return 2; } } public class Three implements SomeNumber { public int getValue() { return 3; } } 

If he does not answer your question, I believe that this is educational material. :-)

+1
source

All Articles