泛型与类<?>

时间:2019-11-20 12:47:55

标签: java jython

是否可以从泛型中实现类以进行类型转换 例如,这对我的buildingObject失败。 tojava (S)在下面的示例中

public abstract class AbstractPythonService implements FactoryBean<IHelloService> {

    public IHelloService getObject() {

        //Here is the actual code that interprets our python file.
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("src/main/python/HelloServicePython.py");
        PyObject buildingObject = interpreter.get("HelloServicePython").__call__();


        //Cast the created object to our Java interface
        return (IHelloService) buildingObject.__tojava__(IHelloService.class);
    }

    @Override
    public Class<?> getObjectType() {
        return IHelloService.class;
    }
}

我想要这样的东西

public abstract class AbstractPythonService<S> implements FactoryBean<S> {

    public S getObject() {

        //Here is the actual code that interprets our python file.
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("src/main/python/HelloServicePython.py");
        PyObject buildingObject = interpreter.get("HelloServicePython").__call__();


        //Cast the created object to our Java interface
        return (S) buildingObject.__tojava__(S.class);
    }

    @Override
    public Class<?> getObjectType() {
        return S.class;
    }
}

1 个答案:

答案 0 :(得分:4)

由于类型擦除,您需要一个Class<S>对象,一些Xyz.class

public abstract class AbstractPythonService<S> implements FactoryBean<S> {
    private final Class<S> type;

    protected AbstractPythonService(Class<S> type) {
        super(type); // Probably the factory would also need the type.
        this.type = type;
    }

    return type.cast(buildingObject.__tojava__(type)); // type.cast probably unneeded.

public Class<S> getObjectType() {
    return type;
}