比较Class对象时的不可比类型

时间:2015-02-26 17:15:41

标签: java factory

我想创建一个工厂,它将类类型作为参数来创建相应的对象实例。

但是这段代码没有编译:

Java代码:

public PropControl Create(Class<? extends PropControl> cls)
{
    if(cls==HouseControl.class) <---- ERROR
    {
       here I create a new instance of HouseControl (that inherits PropControl)
    }
}

我收到此错误:

incomparable types: Class<CAP#1> and Class<HouseControl>
where CAP#1 is a fresh type-variable:
CAP#1 extends PropControl from capture of ? extends PropControl

我如何实现这一目标?

感谢。

2 个答案:

答案 0 :(得分:0)

HouseControl必须扩展PropControl,否则条件永远不会成立,编译器会显示错误。 例如:

    Class<? extends InputStream> clazz = null;
    // error: String does not inherit from InputStream, var will never be true.
    boolean var = clazz == String.class; 

这有效:

    Class<? extends Object> clazz = null;
    boolean var = clazz == String.class;

答案 1 :(得分:0)

如果类HouseControl没有扩展PropControl类,则您提供的代码将无法编译。如果你想要一个更通用的创建代码,你可以查看这段代码,它使用Reflection API作为开始并适应你的需求:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class GenericsCreation {

    public <T> T create(Class<? extends T> cls) throws InstantiationException,
                                                   IllegalAccessException,
                                                   NoSuchMethodException,
                                                   IllegalArgumentException,
                                                   InvocationTargetException {
        Constructor<? extends T> constructor = cls.getConstructor(int.class);
        return constructor.newInstance(1);
    }

    public static void main(String[] args) {
        GenericsCreation test = new GenericsCreation();

        try {
            MyClass instance1  = test.<MyClass>create(MyClass.class);
            MyClass instance1a = test.<MyClass>create(OtherClass.class);
            Object  instance1b = test.<MyClass>create(AnotherClass.class);

            SecondFamilyClass instance2 = test.<SecondFamilyClass>create(SecondFamilyClass.class);
            Object instance2a = test.create(SecondFamilyClass.class);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

class MyClass {
    private int value;
    public MyClass(int param) {
        this.value = param;
    }
}

class OtherClass extends MyClass {
    public OtherClass( int param) {
        super(param);
    }
}

class AnotherClass extends OtherClass {
    public AnotherClass(int param) {
        super(param);
    }
}

class SecondFamilyClass { // Don't extends MyClass
    public SecondFamilyClass(int param) {
        System.out.println("Hey there");
    }
}