Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

反射获取set方法失败 #34

Open
castleKing1997 opened this issue Oct 19, 2021 · 2 comments
Open

反射获取set方法失败 #34

castleKing1997 opened this issue Oct 19, 2021 · 2 comments

Comments

@castleKing1997
Copy link

调用

Method declaredMethod = bean.getClass().getDeclaredMethod(
		"set" + propertyValue.getName().substring(0, 1).toUpperCase()
				+ propertyValue.getName().substring(1), value.getClass());

抛出异常

java.lang.NoSuchMethodException: us.codecraft.tinyioc.HelloWorldServiceImpl.setOutputService(us.codecraft.tinyioc.OutputServiceImpl)

但是HelloWorldServiceImpl有这个set方法

package us.codecraft.tinyioc;

/**
 * @author [email protected]
 */
public class HelloWorldServiceImpl implements HelloWorldService {

    private String text;

    private OutputService outputService;

    @Override
    public void helloWorld() {
        outputService.output(text);
    }

    public void setText(String text) {
        this.text = text;
    }

    public void setOutputService(OutputService outputService) {
        this.outputService = outputService;
    }

    public OutputService getOutputService() {
        return outputService;
    }
}
@castleKing1997
Copy link
Author

定位到java.lang.Class.arrayContentsEq,这个方法的作用是:
在查找方法时,判断参数列表是否相同

  private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
      if (a1 == null) {
          return a2 == null || a2.length == 0;
      }

      if (a2 == null) {
          return a1.length == 0;
      }

      if (a1.length != a2.length) {
          return false;
      }

      for (int i = 0; i < a1.length; i++) {
          // a1: class us.codecraft.tinyioc.OutputServiceImpl@1266
          // a2:interface us.codecraft.tinyioc.OutputService@1265
          if (a1[i] != a2[i]) { 
              return false;
          }
      }
      return true;
  }

OutputService和OutputServiceImpl在判断时是不相等的,所以无法正确定位到set方法

@castleKing1997
Copy link
Author

考虑到这里是反射获取set方法,set方法一般不重名
所以可以考虑只通过方法名反射获取set方法 #35

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant