私有方法获取
老师好,怎么通过反射获取类中的私有方法呢?下面代码只能获取public修辞的方法啊
Method method=employeeClass.getMethod("run"); method.invoke(employee);
13
收起
正在回答 回答被采纳积分+1
1回答
好帮手慕小小
2022-11-15 11:30:23
同学你好,可以通过getDeclaredMethod获取类中的私有方法。参考代码如下:
Employee类:
package com.imooc.reflect.entity; /** * 员工实体类 */ public class Employee { static { System.out.println("Employee类已被加载到jvm,并已初始化"); } private Integer eno; public String ename; private Float salary; private String dname; public Employee(){ System.out.println("Employee默认构造方法已被执行"); } public Employee(Integer eno,String ename,Float salary , String dname){ this.eno = eno; this.ename = ename; this.salary = salary; this.dname = dname; System.out.println("Employee带参构造方法已被执行"); } public Integer getEno() { return eno; } public void setEno(Integer eno) { this.eno = eno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public Float getSalary() { return salary; } public void setSalary(Float salary) { this.salary = salary; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } @Override public String toString() { return "Employee{" + "eno=" + eno + ", ename='" + ename + '\'' + ", salary=" + salary + ", dname='" + dname + '\'' + '}'; } public Employee updateSalary(Float val){ this.salary = this.salary + val; System.out.println(this.ename + "调薪至" + this.salary + "元"); return this; } private String testPrivateMethod(String msg) { return "私有方法执行:" + msg; } public String testPublicMethod(String msg) { return "公共方法执行:" + msg; } }
测试类:
package com.imooc.reflect; import com.imooc.reflect.entity.Employee; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class GetDeclaredSample { public static void main(String[] args) { try { Class<?> employeeClass = Class.forName("com.imooc.reflect.entity.Employee"); // getDeclaredMethods():获取当前运行时类中声明的所有方法。 Method[] declaredMethods = employeeClass.getDeclaredMethods(); for (Method m : declaredMethods) { System.out.println(m); } // 创建employee对象 Constructor<?> constructor = employeeClass.getConstructor(Integer.class, String.class, Float.class, String.class); Employee employee = (Employee) constructor.newInstance(100, "李磊", 3000f, "研发部"); //获取类中指定方法 /* 1.获取指定的某个方法 getDeclaredMethod():参数1-指明获取的方法的名称 参数2-指明获取的方法的形参列表 */ Method testPrivateMethod = employeeClass.getDeclaredMethod("testPrivateMethod", String.class); /* 2.保证当前方法是可访问的 */ testPrivateMethod.setAccessible(true); /* 3.调用方法的invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参 invoke()的返回值即为对应类中调用的方法的返回值。 */ Object returnValue = testPrivateMethod.invoke(employee, "private测试"); System.out.println(returnValue); } catch (Exception e) { e.printStackTrace(); } } }
祝学习愉快~
相似问题
登录后可查看更多问答,登录/注册
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星