List of Classes implementing an Interface

爱⌒轻易说出口 提交于 2019-12-13 11:43:19

问题


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. :-)



来源:https://stackoverflow.com/questions/13838472/list-of-classes-implementing-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!