gpt4 book ai didi

java - 无法反射(reflect)。异常 java.lang.IllegalArgumentException : object is not an instance of declaring class

转载 作者:行者123 更新时间:2023-12-02 06:26:31 24 4
gpt4 key购买 nike

我有两个不同的类,一个是使用下面的验证方法。

@Validator
public boolean validIdentifier() throws IllegalArgumentException, IllegalAccessException{
boolean flag=false;
Field[] fields=this.data.getClass().getDeclaredFields();
for(Field field : fields) {
if (!field.isAccessible()){
field.setAccessible(true);
}
if (field.getName().endsWith("Identifier") && field.get(data)!=null){
flag=true;
field.setAccessible(false);
break;
}
field.setAccessible(false);
}
return flag;
}

另一种方法有两种反射(reflect)上述验证方法的方法,如下所示

public void validate(){
AppValidator validator=new AppValidator(somebean);
doCommonValidation(validator.getClass());
}

public void doCommonValidation(Class clazz){
Method[] methods = clazz.getMethods();
for(Method method:methods) {
for(Annotation annotation:method.getAnnotations()){
try {
if (annotation instanceof Validator && !(boolean)method.invoke(clazz)){ //exception is here
String errorMessage = ((Validator)annotation).message();
String display=((Validator)annotation).displayField();
if(errorMessage != null) {
System.out.println(display+":"+errorMessage);
}
}
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
}

}

上面的代码抛出java.lang.IllegalArgumentException:对象不是声明类的实例。

如果我像这样更改 doCommonValidation 并绕过验证方法,则一切正常。

public void validate() {
try {
AppValidator validator=new AppValidator(someBean);
Method[] methods = validator.getClass().getMethods();
for(Method method:methods) {
for(Annotation annotation:method.getAnnotations()){
if (annotation instanceof ValidatingMethod && !(boolean)method.invoke(validator)){
String errorMessage = ((ValidatingMethod)annotation).message();
String display=((ValidatingMethod)annotation).displayField();
if(errorMessage != null) {
System.out.println(display+":"+errorMessage);
}
}
}
}

} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) {
e.printStackTrace();
return new HashMap<String, String>();
}
}

问题是我确实需要能够插入几个不同的验证类。如果我明确地实例化它们,那么我必须编写重复的代码,其中唯一的区别是我反射(reflect)的类。

我不明白为什么在第一种情况下我得到了异常,而在第二种情况下却没有。有什么想法吗?

谢谢

最佳答案

当您在错误的情况下执行此行时:

if (annotation instanceof Validator && !(boolean)method.invoke(clazz))

您需要传递到invoke method 表示要调用该方法的对象的参数,因为它是实例方法。此参数的类型应由 Class 表示。实例作为参数传递给 doCommonValidation(Class)方法。你传递的是 Class<T> 的一个实例,而不是 的实例。

关于java - 无法反射(reflect)。异常 java.lang.IllegalArgumentException : object is not an instance of declaring class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20477390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com