我不知道這是否可以在Java中完成。我找不到解決方案。檢查方法參數的泛型類型
我想檢查一個類中的所有方法,並找出該方法的參數如何與通用信息相似。例如,如果你有一個接口,像下面的實施者:
// Services are the objects i will examine
public interface Service<T extends DetailsModel> {
public Response findObject(RequestEvent<T> event);
}
public interface SomeObjectService extends Service<SomeObject> {
Response findObject(RequestEvent<SomeObject> event);
}
public class SomeObjectServiceImpl extends SomeObjectService {
public Response findObject(RequestEvent<SomeObject> event) {...}
}
// Events are the parameters of the services
public interface Event<T extends DetailsModel> {
Callback getCallback()
}
public abstract class AbstractEvent<T> implements Event<T> {
public Callback getCallback() {
return null;
}
}
public class RequestEvent<T> extends AbstractEvent<T> {
Handle<T> t;
public Handle<T> getHandle() {...}
}
看着SomeObjectServiceImpl時,我已經嘗試了所有樣的東西得到實際的T出RequestEvent的。例如
public <D extends DetailsModel> void configure(Service<D> service) {
Method[] allDeclaredMethods = service.getClass().getDeclaredMethods();
for (Method declaredMethod : allDeclaredMethods) {
try {
Type[] parameterTypes = declaredMethod.getGenericParameterTypes();
if (parameterTypes.length == 1) {
Type parameterType = parameterTypes[0];
if (Event.class.isAssignableFrom((Class<?>) parameterType)) {
ParameterizedType type = ((ParameterizedType) ((Class) parameterType).getGenericSuperclass());
Type genericType = type.getActualTypeArguments()[0];
if (genericType != null && genericType instanceof Class) {
EventDescriber eventDescriber = new EventDescriber(
(Class<? extends Event>) parameterType,
(Class) genericType);
}
}
}
} catch (Exception e) {
logger.warn("Could not map " + declaredMethod, e);
}
}
然後我想追問的SomeObjectServiceImpl的方法是這樣的結果:
ServiceImpl:
findObject:
RequestEvent
SomeObject (I cant find this. Instead I find a TypeVariableImpl.)
你能與Java反射做到這一點?
@AnAmuser您檢索哪個'方法? – 2014-10-05 18:13:12
這也行不通。 type.getActualTypeArguments()[0]返回一個TypeVariableImpl(name =「T」,bounds = null,...)。這發生在兩種方法上。如果這有所幫助,我會使用新的ServiceImpl()。getClass()。getMethod(..)。 – AnAmuser 2014-10-05 18:28:52
@AnAmuser什麼是'ModelServiceImpl'?我要解決你的問題。 – 2014-10-05 18:30:51