一.通过反射获取构造方法并使用

  获取构造方法
    getConstructors
    getDeclaredConstructors
  创建对象
    newInstance()
    con.newInstance(“zhangsan", 20);

二.通过反射获取成员变量并使用

  获取所有成员
    getFields,getDeclaredFields
  获取单个成员
    getField,getDeclaredField
  修改成员的值
    set(Object obj,Object value)
     将指定对象变量上此 Field 对象表示的字段设置为指定的新值。

三.通过反射获取成员方法并使用

  获取所有方法
    getMethods
    getDeclaredMethods
  获取单个方法
    getMethod
    getDeclaredMethod
  暴力访问(否则会报Illegalxxx...Exception...)
    method.setAccessible(true);

注意:

  getDeclaredConstructors, getDeclaredFields, getDeclaredMethods, 这里加Declared是可以获取非public声明的构造方法, 成员变量, 成员方法.(否则会报NoSuch.....Exception...)

四.示例

4.1 首先自定义Person类

 1 package cn.itcast_01;
 2 
 3 public class Person {
 4     private String name;
 5     int age;
 6     public String address;
 7 
 8     public Person() {
 9     }
10 
11     private Person(String name) {
12         this.name = name;
13     }
14 
15     Person(String name, int age) {
16         this.name = name;
17         this.age = age;
18     }
19 
20     public Person(String name, int age, String address) {
21         this.name = name;
22         this.age = age;
23         this.address = address;
24     }
25 
26     public void show() {
27         System.out.println("show");
28     }
29 
30     public void method(String s) {
31         System.out.println("method " + s);
32     }
33 
34     public String getString(String s, int i) {
35         return s + "---" + i;
36     }
37 
38     private void function() {
39         System.out.println("function");
40     }
41 
42     @Override
43     public String toString() {
44         return "Person [name=" + name + ", age=" + age + ", address=" + address
45                 + "]";
46     }
47 
48 }
View Code

相关文章:

  • 2021-09-23
  • 2022-12-23
  • 2021-12-23
  • 2021-10-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-19
相关资源
相似解决方案