List of Classes implementing an Interface

2019-03-26 17:36发布

问题:

Is there a way to implement something like

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

my goal is to create a hashmap from that list, where the keys are the toString methods of the class (defined in MyInterface) and the values are the classes itself. The toString method of every object of this class returns the same result. This way I could create Instances of the classes using the map by searching the right strings.

thank you for trying to help, greetings

回答1:

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

should be

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

there is no implements keyword in the world of generics. if you want a type parameter that implements an interface , use the extends keyword to represent it.



回答2:

Since you seem interested by the way I explained, here is a quick implementation, to verify it 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 it doesn't answer your question, consider it as educational material, I hope. :-)