java之反射

1.反射的基本概念

好比驾车时的后视镜,可以通过光的反射来看到后车的大小车牌号甚至驾驶员.Java中的反射可以让我们通过其看到类的三个基本要素(属性,方法,构造方法)

一.得到类对象

有三种方式

(1)通过对象的地址得到

Class c1=Class.forName("com.xxx.xxx.类名");

(2)通过对象的自身属性得到

Class c2=String.class;//得到String的类对象

(3)通过实例的方法得到

String str="xxx";

Class c3=str.getClass();

2.通过类对象反推属性,方法,构造方法(以c1为例)

Field [ ] fields=c1.getDeclaredField();//得到属性数组,数组里存的是属性

Method[ ]methods=c1.getDeclaredMethod();

Constructor [ ]constructs=c1.getDeclaredConstructor();

3.通过名字拼成get/set方法

String steMethod="set"+Character.toUpperCase(fieldName.charAt[0])+fieldName.substring(1);//之后根据名字来得到方法并使用

原文地址:https://www.cnblogs.com/waibangma/p/11130273.html