User 类:
public class User {
private String userName;
private int userAge;
public String location;
public User() {
}
public User(String userName, int userAge, String location) {
this.userName = userName;
this.userAge = userAge;
this.location = location;
}
// private modifier
private User(int userAge) {
this.userAge = userAge;
}
/*only the name is different, can not constitute an overload,
so it can not add the constructor that only have a location parameter.*/
public User(String userName) {
this.userName = userName;
}
public User(String userName, String location) {
this.userName = userName;
this.location = location;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public void testMethod () {
System.out.println("hello!");
}
private void testWay () {
System.out.println("overload");
}
public void testWay (int id) {
System.out.println(id);
}
@Override
public String toString() {
/* Considering code writing from the bottom level, in order to cope with different functional requirements */
return "User{" +
"userName='" + this.getUserName()+ '\'' +
", userAge=" + this.getUserAge()+
", location='" + this.getLocation() + '\'' +
'}';
}
}
通过反射调用方法测试类:
public class GetMethodTest02 {
public static void main(String[] args) {
User user01 = new User();
Class classObject01 = user01.getClass();
Class classObject02 = User.class;
Class classObject03 = null;
try {
classObject03 = Class.forName("com.bjsxt.demo.User");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
/* call the public method */
Method method01 = null;
try {
method01 = classObject03.getDeclaredMethod("testWay",int.class); // get designed method object.
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
Object user02 = null;
try {
user02 = classObject03.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
method01.invoke(user02,3);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// how call the private method?
}
}
老师,在调用方法的测试类中,如何调用自定义的用 private 修饰的 testWay() 方法?还是说通过反射只能调用类的 public 方法,不能调用 pirvate 的方法.