为什么调用不了私有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);
}
}
创建类实例的时候就会调用类构造器
你除了print方法是私有的,构造函数也是私有的,构造器也设置成可访问就行,
Constructor declaredConstructor = emp.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
要不然把Test类的main方法移到Employee类中也行
谢谢 好了 十分感谢
为什么啊 是因为使用构造器创建对象的吗
感谢 感谢 懂了懂了
您好 不好意思 我想问一下 创建类实例的时候就会调用类构造器 调用的是无参的构造方法吗 要是没有无参的的构造方法呢
我知道了 没有无参构造方法 是创建实例时必须要有属性是这样吗 麻烦了麻烦了 打扰了
你没有定义构造函数的话会生产默认的无参构造函数,如果定义了有参构造的话调用构造函数的时候要传参数,想要调用无参构造的话就要手动添加无参构造函数