-2

忽略这个问题

我有一个扩展通用超类的子类。这里是

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

ColorPainter 画家是一个抽象类,它具有未实现的方法 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 实例。喜欢

字符串颜色=“任何”;//xxx可以是蓝色,红色,绿色

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

我想要一个等效于上述 if else 条件的实现方法。

我编写了一些使用 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");
4

2 回答 2

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

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

于 2013-07-17T10:58:21.120 回答
-1

您可能不了解泛型的意图。此外,你让它太复杂了。

试试这个,但请记住添加修饰符,如publicor private

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");
  } 
}
于 2013-07-17T05:37:32.870 回答