List of Classes implementing an Interface

前端 未结 2 1308
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 14:55

Is there a way to implement something like

    List> ClassList = new ArrayList

        
相关标签:
2条回答
  • 2021-02-15 15:13
    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.

    0 讨论(0)
  • 2021-02-15 15:14

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

    0 讨论(0)
提交回复
热议问题