Search code examples
javajython

Generics vs Class<?>


Is it possible to get implement the class from the generic for type casting for example this fail for me buildingObject.tojava(S) in below example

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

I want something like this

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

Solution

  • Because of type erasure you need a Class<S> object, some 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;
    }