为什么调用不了私有print方法 异常说权限不够
public class Employee {
private String name;
public String sex;
protected int age;
double salary;
private Employee() {
super();
}
public Employee(String name, String sex, int age, double salary) {
super();
this.name = name;
this.sex = sex;
this.age = age;
this.salary = salary;
}
public void show(String name) {
System.out.println("员工信息如下:姓名="+name+",性别="+sex+",年龄="+age+",薪资"+salary);
}
private String print() {
return "How are you!";
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Test {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
//获取Class对象
Class emp=Employee.class;
//修饰符
int i=emp.getModifiers();
String str=Modifier.toString(i);
System.out.println("访问修饰符"+str);
//包名
Package package1=emp.getPackage();
System.out.println("包名"+package1);
//全限定名
String str2=emp.getName();
System.out.println("全限定名"+str2);
//类名
String str3=emp.getSimpleName();
System.out.println("类名"+str3);
//public修饰的构造方法数量
Constructor[] constructors=emp.getConstructors();
int num=0;
for (Constructor constructor : constructors) {
num++;
}
System.out.println("public修饰的构造方法数量"+num);
//获取有参构造方法的参数个数。
Constructor[] declaredConstructors=emp.getDeclaredConstructors();
for (Constructor constructor : declaredConstructors) {
int num2=constructor.getParameterCount();
if(num2>0) {
System.out.println("有参构造方法的参数个数"+num2);
}
}
//获取类中所有public成员变量的个数
Field[] field=emp.getFields();
int num3=0;
for (Field field2 : field) {
num3++;
}
System.out.println("获取类中所有public成员变量的个数"+num3);
//本类中所有成员变量的个数
Field[] declaredfields=emp.getDeclaredFields();
int num4=0;
for (Field field2 : declaredfields) {
num4++;
}
System.out.println("本类中所有成员变量的个数"+num4);
//根据方法名获取print方法,并通过相关方法调用显示方法的返回值
Method[] method=emp.getDeclaredMethods();
for (Method method2 : method) {
System.out.println(method2);
}
//创建对象
Object obj= emp.getDeclaredConstructor().newInstance();
Method print=emp.getDeclaredMethod("print");
print.setAccessible(true);
Object invoke = print.invoke(obj);
System.out.println(invoke);
}
}