如何在Class.class中使用泛型

时间:2015-05-13 04:19:09

标签: java class reflection

我想避免警告:

“类型安全类型的表达式需要未经检查的转换以符合类”

从这句话:

Class<MyInterface> cc = interpreter.get("Myclass", Class.class );

我试过了:

Class<MyInterface> cc = interpreter.get("Myclass", Class<MyInterface>.class );

但无效。

如果没有@SuppressWarnings(“未选中”)

,我该怎么做呢?

interpreter.get的签名:

T interpreter.get(String name, Class<T> javaClass)

背景: 我使用库Jython并在Python中定义了一个实现MyInterface的类,然后我用Java捕获这个类,然后创建它们的实例。这就是为什么我需要类本身,而不是类的实例。

代码如下:

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("from cl.doman.python import MyInterface");
....
interpreter.exec(pythonCode);
Class<MyInterface> cc = interpreter.get("Myclass", Class.class);
MyInterface a = (MyInterface) cc.newInstance();

我的代码工作正常但我无法抑制警告。

2 个答案:

答案 0 :(得分:2)

可能

Class<?> clazz = interpreter.get("Myclass", Class.class); 
Class<? extends MyInterface> cc = clazz.asSubclass(MyInterface.class);
// look, Ma, no typecast!
MyInterface a = cc.newInstance();

答案 1 :(得分:-1)

更新鉴于问题的新上下文(使用PythonInterpreter),我的答案的内容将是通用的T get(String name, Class<T> javaClass),而不是用于PythonInterpreter。

我写了一个小例子和一个简单的&#34;口译员&#34;根据您的示例定义简单方法的类。给出你的例子get方法。我希望它返回T而不是Class<T>

以下示例还让我想起了一个(非常简单的)Spring Bean加载示例,您可以在其中加载具体实现并返回接口。

public class Test {

    public static void main(String[] args) {
        final Interperter<MyInterface> interperter = new Interperter<MyInterface>() ;
        final MyInterface i = interperter.get("MyClass", MyInterface.class);
        System.out.println(i);
    }

    public static class Interperter<T> {
        // A sample get method with the same signature, The body's contents shouldn't matter to much for this demonstration.
        public T get(String name, Class<T> javaClass) {
            try {
                final Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass(name);
                return (T) clazz.newInstance();
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

}

示例界面

public interface MyInterface {}

示例基类

public final class MyClass implements MyInterface {

    @Override
    public String toString() {
        return "MyClass{}";
    }
}

节目输出:MyClass{}

如果你觉得我误解了你的问题,请告诉我。)