Method相关操作
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class User {
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
public User(){
}
public User(String name){
this.name=name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static void main(String[] args) throws NoSuchMethodException {
try {
Class<?> clazz=Class.forName("com.fanyinhang.demo.User");
User user = null;
try {
user = (User)clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Method[] methods = clazz.getMethods();
Method[] declaredMethods = clazz.getDeclaredMethods();
Method getName = clazz.getMethod("getName");
Method setName = clazz.getDeclaredMethod("setName",String.class);
Class<?> returnType = method.getReturnType();
try {
setNamename1.setAccessible(true);
setName.invoke(user,"hello");
System.out.println(user);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
输出
User{name='hello'}