1.コード
package com.schoolonline.reflect;
public class ReflectEntity {
private String name = "java";
private Integer year = 23;
private String email;
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private void sayHello() {
System.out.println("Hi, everyone!\n my name is " + getName() + ", this is " + getYear() + " years old!");
}
@Override
public String toString() {
return "ReflectEntity{" +
"name='" + name + '\'' +
", year=" + year +
", email='" + email + '\'' +
'}';
}
}
package com.schoolonline.reflect;
import java.lang.reflect.Method;
public class ReflectMain {
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("com.schoolonline.reflect.ReflectEntity");
Method method = clazz.getDeclaredMethod("sayHello");
method.setAccessible(true);
method.invoke(clazz.newInstance());
}
}
結果
Hi, everyone!
my name is java, this is 23 years old!
Process finished with exit code 0
プライベートメソッドやプロパティを呼び出すと、method.setAccessible(真)に設定されていないこと2.注;
異常として報告されます
Exception in thread "main" java.lang.IllegalAccessException: Class com.schoolonline.reflect.ReflectMain can not access a member of class com.schoolonline.reflect.ReflectEntity with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
at java.lang.reflect.Method.invoke(Method.java:491)
at com.schoolonline.reflect.ReflectMain.main(ReflectMain.java:9)
3.参照