Search code examples
javageneric-programming

getting instance of generic subclasses using its reference


Ignore this question

I have a subclass which extends generic super class. Here it is

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

ColorPainter painter is an abstarct class which has unimplemented method paint().

I have declared enum with

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;
    }
}  

When color name is passed,the method should return the appropriate colorPainter Instance. like

String color="any"; //xxx can be blue,red,green

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

I want an implementation method which is equivalent to above if else condition.

I have written some code making use of Enum class ColorsUsage. But could not complete it.

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

please fill the "?" and the commented line.

how to call that method.

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

Solution

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

    In above method; instead of using Generics you can return Object (i.e. super class) and then using instanceof keyword you can find the exact type of the instance in the calling method.