gpt4 book ai didi

java - 泛型与类

转载 作者:行者123 更新时间:2023-12-01 17:42:49 24 4
gpt4 key购买 nike

是否可以从泛型中实现类以进行类型转换例如,在下面的示例中,这对我来说构建Object.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;
}
}

最佳答案

由于类型删除,您需要 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;
}

关于java - 泛型与类<?>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58954732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com