Skip to content

只通过方法名反射获取set方法 #35

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,23 @@ protected void applyPropertyValues(Object bean, BeanDefinition mbd) throws Excep
value = getBean(beanReference.getName());
}

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

declaredMethod.invoke(bean, value);
} catch (NoSuchMethodException e) {
Field declaredField = bean.getClass().getDeclaredField(propertyValue.getName());
declaredField.setAccessible(true);
declaredField.set(bean, value);
Method[] declaredMethods = bean.getClass().getDeclaredMethods();
boolean hasMethod = false;
for (Method declaredMethod : declaredMethods) {
if (declaredMethod.getName().equals("set"
+ propertyValue.getName().substring(0, 1).toUpperCase()
+ propertyValue.getName().substring(1))) {
declaredMethod.setAccessible(true);
declaredMethod.invoke(bean, value);
hasMethod = true;
break;
}
}
}
}
if (!hasMethod) {
Field declaredField = bean.getClass().getDeclaredField(propertyValue.getName());
declaredField.setAccessible(true);
declaredField.set(bean, value);
}
}
}
}
3 changes: 1 addition & 2 deletions src/test/java/us/codecraft/tinyioc/OutputServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
* @author yihua.huang@dianping.com
*/
public class OutputServiceImpl implements OutputService {

private HelloWorldService helloWorldService;
@Override
public void output(String text){
System.out.println(text);
}

}