简体   繁体   English

Java反射,从超类调用方法?

[英]Java reflection, call method from superClass?

I've seen a lot of examples, and I know what has been discussed.我看过很多例子,我知道讨论了什么。 I do everything right, but I receive an error.我做的一切都正确,但我收到一个错误。 Why is that?这是为什么? What am i doing wrong?我究竟做错了什么?

Class superClass = rootObject.getSuperclass();
Method addErrorMethod = superClass.getDeclaredMethod("addErrorMessage", ErrorType.class, String.class, String.class, String.class);
_log.info(addErrorMethod.getName());
addErrorMethod.invoke(superClass, ErrorType.FIELD, propertyName, message, "");

I get method, but when you call the invoker.我得到方法,但是当你调用调用者时。 I get the following error.我收到以下错误。

 java.lang.IllegalArgumentException: object is not an instance of declaring class

Thanks.谢谢。

When you call Method.invoke the first parameter must be either:当您调用Method.invoke ,第一个参数必须是:

  • when method is non-static instance of the class which contains the method当方法是包含该方法的类的非静态实例时
  • when method is static null or class itself.当方法为静态null或类本身时。

Since you pass the class itself and you got error it suggests that method you are trying to invoke is not static, so you should invoke it like由于您传递了类本身并且出现错误,这表明您尝试调用的方法不是静态的,因此您应该像这样调用它

addErrorMethod.invoke(rootObject, ErrorType.FIELD, propertyName, message, "");
//                    ^^^^^^^^^^- assuming it is instance on which we want to invoke this method

You did not do everything right:你没有做对每一件事:

addErrorMethod.invoke(superClass, ErrorType.FIELD, propertyName, message, "");

should read应该读

addErrorMethod.invoke(rootObject, ErrorType.FIELD, propertyName, message, "");

superClass is an instance of Class , to which has no addErrorMessage() method, as the error message is telling you. superClassClass一个实例,其中没有addErrorMessage()方法,正如错误消息告诉您的那样。 The first parameter to the method is a reference to the object that will be used as this within the method.该方法的第一个参数是对将在该方法中用作this的对象的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM