使用其引用获取泛型子类的实例

时间:2013-07-17 05:21:39

标签: java generic-programming

忽略此问题

我有一个扩展泛型超类的子类。这是

BlueColorPainter extends ColorPainter<BlueColor>;
GreenColorPainter extends ColorPainter<GreenColor>;
RedColorPainter extends ColorPainter<RedColor>;

ColorPainter画家是一个abstarct类,它有未实现的方法paint()。

我用

声明了枚举
class enum ColorsUsage{
    BLUE("blue","BlueColorPainter","BlueColor"),
    Green("green","GrerenColorPainter","GreenColor"),
    Red("red","RedColorPainter","RedColor");

    String colorName,colorPainterClass,colorClass;
    ColorPainters(String colorName, String colorPainterClass,String colorClass) {
        this.colorName = colorName;
        this.colorPainterClass = colorPainterClass;
        this.colorClass = colorClass;
    }
}  

传递颜色名称时,该方法应返回相应的colorPainter实例。 像

String color =“any”; // xxx可以是蓝色,红色,绿色

ColorPainter<?> colorPainter;
if(color=="blue")   
colorPainter=new BlueColorPainter();
else if(color=="red")   
colorPainter=new RedColorPainter();
if(color=="green")   
colorPainter=new GreenColorPainter();

我想要一个与上面相同的实现方法if else condition。

我编写了一些使用Enum类ColorsUsage的代码。但无法完成它。

public static ? getPainter(String color){
       for(ColorsUsage cp:ColorsUsage.values()){
         //write code to create the instance of painter class, ex:BlueColorPainter 
       }
    }

请填写“?”和评论说明。

如何调用该方法。

ColorPainter<?> painter= getPainter("blue");

2 个答案:

答案 0 :(得分:1)

 public static ? getPainter(String color){
   for(ColorsUsage cp:ColorsUsage.values()){
     //write code to create the instance of painter class, ex:BlueColorPainter 
   }
 }

以上方法;您可以返回Object(即超类),然后使用instanceof关键字,而不是使用Generics,您可以在调用方法中找到实例的确切类型。

答案 1 :(得分:-1)

你可能不理解泛型的意图。 另外你太复杂了。

试试这个,但请注意添加publicprivate等修饰符:

class ColorPainters{

  static ColorPainters BLUE = new ColorPainters("blue","BlueColorPainter","BlueColor"),
                       GREEN = new ColorPainters("green","GreenColorPainter","GreenColor"),
                       RED = new ColorPainters("red","RedColorPainter","RedColor");

  String colorName, colorPainterClass, colorClass;

  public ColorPainters(String name,String painter,String color){
      this.colorName=name;
      this.colorPainterClass= painter;
      this.colorClass=color;
 }  

  public static ColorPainters getPainter(String color){
      if(color.equals(BLUE.colorName))
          return BLUE;
      else if(color.equals(GREEN.colorName))
          return GREEN;
      else if(color.equals(RED.colorName))
          return RED;
      else
          return new ColorPainters(color, color + "ColorPainter", color + "Color");
  } 
}