我有一個class( CreateAccountRequest) 實作了一個interface( Iloggable),介面沒有方法,僅用于標記目的。
public interface Iloggable {}
public class CreateAccountRequest implements Iloggable{
//some private fields, getters and setters
}
在我的自定義RequestBodyAdviceAdapter類中,嘗試檢查請求是否是 Iloggable 的實體,繼續或忽略請求(例如是否進行日志記錄)
我知道我們可以使用instanceOf運算子來檢查一個物件是否實作了一個介面,并且下面的單元測驗批準它:
@Test
void CreateAccountRequest_Object_Instance_Of_Iloggable_Test() {
CreateAccountRequest request = new CreateAccountRequest();
assertTrue(request instanceof Iloggable);
}
但是在RequestBodyAdviceAdapter支持方法中,結果一直是false或true,我嘗試了不同的方法來區分引數是否實作了介面
@ControllerAdvice
public class CustomRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {
@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
//if(methodParameter.getParameterType().isInstance(Iloggable.class)) //return false all the time
//if(methodParameter.getParameter().getType().isInstance(Iloggable.class))// return false all the time
if(methodParameter.getParameter().getClass().isInstance(Iloggable.class))// return false all the time
// if(type instanceof Iloggable)// return false all the time
//if(type.getClass().isInstance(Iloggable.class)) //return true all the time
//if(type != null && Iloggable.class.isAssignableFrom(type.getClass()))//return false all the time
return true;
return false;
}
//other override methods
}
為了消除任何疑問,我在支持方法中放了一個除錯快照:

uj5u.com熱心網友回復:
您想確保該型別表示一個實作 Illoggable 的類。
@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
if ( type instanceof Class ) {
cls = ( Class ) type;
result = Iloggable.class.isAssignableFrom( cls );
} else {
result = false;
}
return result;
}
uj5u.com熱心網友回復:
在這種情況下type是java.lang.reflect.Type(實體)而不是CreateAccountRequest(實體;)
您可以通過以下方式獲得更多幸運:
if (type instanceof Class) { // type != null
Class<?> aClazz = (Class<?>) type;
return Iloggable.class.isAssignableFrom(aClazz);
}
Class.isAssignableFrom(...)-javadoc-17
型別 -> 類
深入:
-
if(type instanceof Iloggable) //always false, because type is the // (java.lang.reflect.)Type(->class) (occasionally) of the Iloggable and not/ever an instance of it. -
if(type.getClass().isInstance(Iloggable.class)) //equivalent to // java.lang.reflect.Type.class.isInstance(Iloggable.class) // always false, except when Iloggable *implements* Type (pervert, but possible!;) -
Iloggable.class.isAssignableFrom(type.getClass()) //incorporates // my "wrong assumptions" on type... type.getClass() would // evaluate to java.lang.reflect.Type.class, which is similar to bullet 2
但我假設(正確使用時 -> 實驗)一些MethodParameter方法也應該導致所需的。尤其:
getParameterType()getGenericParameterType()
uj5u.com熱心網友回復:
嘗試以下比較, target.getTypeName()==Iloggable.class.getTypeName()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/352939.html
