我有这种方法来获取我的服务
public <T extends ServiceInterface> T getService(Class<T> aServiceClass);
我想用此方法实例化类“MyService”,该类扩展到 ServiceInterface。
如何做到这一点?我应该创建一个 new MyService
对象将其作为参数传递吗?但如果我这样做,获取服务方法将没有用处。
最佳答案
如果我理解你的问题,你想创建一个类 MyService
,延伸ServiceInterface
。并且您想通过方法 getService(Class<T> aServiceClass>)
获取您的服务, 正确的?看起来像这样(但请将类拆分到不同的文件中):
package test;
public class Test2 {
public static void main(String[] args) {
MyService m = getService(MyService.class);
//m.someMethod(...);
}
public static <T extends ServiceInterface> T getService(Class<T> aServiceClass) {
return null; //??
}
//class MyService
public class MyService extends ServiceInterface{
//someMethods...
}
//class ServiceInterface
public class ServiceInterface {
public <T extends ServiceInterface> T getService(Class<T> aServiceClass) {
return null; //whatever the method is doing
}
}
}
关于Java - 使用以 Class<T> 作为参数的 getService 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56257133/