反射Field、Method、Constructor

2022-12-08 21:48:32 530 转载:kaotop.com/it/1077896.html
一些要用到的方法:

getFields():获取public修饰的属性

getDeclaredFields():获取所有属性

getModifiers():获取修饰符(输出时要用Modifier.toString()包裹)

getType():获取属性的类型,返回Class类型,输出需要.getName()

getReturnType():获取方法的返回值类型

getName():获取完整类名

getSimpleName():获取简单类名称

getParameterTypes():获取参数列表的数据类型,返回值是个数组类型


一、反射Field (通过反射机制访问属性很重要)

Student.java


main:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

try{

Class studentClass = Class.forName("com.example.test.Student");

Object obj = studentClass.newInstance();


Field[] fields = studentClass.getFields();

System.out.println(fields.length);

Field[] fs = studentClass.getDeclaredFields();

System.out.println(fs.length);


for(Field field: fs) {

System.out.println(Modifier.toString(field.getModifiers())+" "+field.getType().getSimpleName() +" "+field.getName());

}


Field noField = studentClass.getDeclaredField("no");

Field nameField = studentClass.getDeclaredField("name");

Field sexField = studentClass.getDeclaredField("sex");

Field ageField = studentClass.getDeclaredField("age");


noField.set(obj,201883);

nameField.setAccessible(true);

nameField.set(obj,"宇航员");

sexField.set(obj,true);

ageField.set(obj,21);

System.out.println(noField.get(obj) +" "+ nameField.get(obj) +" "+ sexField.get(obj) +" "+ ageField.get(obj));


}catch(ClassNotFoundException e) {

e.printStackTrace();

}catch(IllegalAccessException e) {

e.printStackTrace();

}catch(InstantiationException e) {

e.printStackTrace();

}catch(NoSuchFieldException e) {

e.printStackTrace();

}

二、反射Method

Method.java:


main:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

try{

Class methodClass = Class.forName("com.example.test.Method");

Object m = methodClass.newInstance();

Method[] ms = methodClass.getDeclaredMethods();//可获取到私有方法

System.out.println(ms.length);

for(Method method:ms) {

System.out.println(Modifier.toString(method.getModifiers()) +" "+

method.getReturnType().getSimpleName() +" "+ method.getName() +"{n"+

method.getParameterTypes());//parameter返回的是数组,通过for循环输出

}


}catch(ClassNotFoundException e) {

e.printStackTrace();

}catch(IllegalAccessException e) {

e.printStackTrace();

}catch(InstantiationException e) {

e.printStackTrace();

}

三、反射机制调用方法(非常重要)

1

2

3

4

5

Classclass= Class.forName("com.example.test.Method");

Object obj =class.newInstance();

Method method =class.getDeclaredMethod("m1",String.class,Stringclass);


Object retValue = method.invoke(obj,"admin","123");

四、反射Constructor

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

publicclassVip{

intno;

String name;

String birth;

booleansex;


publicVip(){

}


publicVip(intno){

this.no = no;

}


publicVip(intno,String name){

this.no = no;

this.name = name;

}


publicVip(intno,Srting name,String birth){

this.no = no;

this.name = name;

this.birth = birth;

}


publicVip(intno,String name,String birth,booleansex){

this.no = no;

this.name = name;

this.birth = birth;

this.sex = sex;

}

}

main:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

//反编译一个类的构造方法

StringBuilder s =newStringBuilder();

Class vipClass = Class.forName("com.syf.java.bean.Vip");

s.append(Modifier.toString(vipClass.getModifiers()));

s.append(" class");

s.append(vipClass.getSimpleName());

s.append("{n");

s.append("}");

System.out.println(s);


Constructor[] constructors = vipClass.getDeclaredConstructors();

for(Costructor construtor : constructors){

s.append("t");

s.append(Moifier.toString(constructor.getModifiers()));

s.append(" ");

s.append(vipClass.getSimpleName());

s.append("(");

Class[] parameterTypes = constructor.getParameterTypes();

for(Class parameterType : parameterTypes){

s.append(parameterType.getSimpleName());

s.append(",");

}

//删除最后下标位置上的字符

if(parameterTypes.length ;0){

s.deleteCharAt(s.length()-1);

}

s.append("){}n");

}

通过反射机制调用构造方法(非重点)

1

2

3

4

5

Class c = Class.forName("com.syf.java.bean.Vip");

Object obj = c.newInstance();

Constructor con = c.getDeclaredConstructor(int.class,String.class,String.class,boolean.class);

Object newObj = con.newInstance(110,"jackson","2000-02-02",true);

System.out.println(newObj);//要重写Vip的toString方法

五、获取类的父类和父接口(重点)

1

2

3

4

5

6

7

Class stringClass = Class.forName("java.lang.String");

Class superClass = stringClass.getSuperClass();

System.out.println(superClass.getName());

Class[] interfaces = stringClass.getInterfaces();

for(Class in : interfaces){

System.out.println(in.getName());

}

*特别说明:本文来自网络,如有侵权,请联系我们删除,非常感谢!