最近看源碼時(shí)發(fā)現(xiàn)很多地方使用的反射機(jī)制,一直對(duì)這個(gè)反射機(jī)制不太清楚蜓竹,今天花一點(diǎn)時(shí)間看了看荆几,敲了敲反射的使用方法;
兩個(gè)類:Main.class嗜历,Person.class;
Main.class實(shí)現(xiàn)各種方法的測試宣渗。
Person三個(gè)私有成員變量:name、age梨州、sex痕囱;其中sex的set方法為私有方法;其他getter和setter都是public;兩個(gè)構(gòu)造函數(shù)暴匠,一個(gè)無參數(shù)鞍恢,一個(gè)參數(shù)為name和age;
package reflect;
public class Person {
private String name;
private int age;
private String sex;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
public void sayPerson(String name, int age) {
System.out.println(name+ " " + age);
}
@Override
public String toString() {
return getName() + " " + getSex() + " " + getAge();
}
}
構(gòu)造函數(shù)的反射調(diào)用
public static void testConstructor() {
Class<?> person = null;
try {
//獲取到類對(duì)象
person = Class.forName("reflect.Person");
} catch (Exception e) {
e.printStackTrace();
}
try {
//獲取構(gòu)造函數(shù)(String,int)
Constructor cons = person.getConstructor(String.class,int.class);
System.out.println(cons.newInstance("AA", 15));
//獲取無參構(gòu)造函數(shù)()
Constructor cons2 = person.getConstructor();
System.out.println(cons2.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
//獲取構(gòu)造函數(shù)列表
Constructor<?>[] t = person.getConstructors();
for (Constructor a : t)
System.out.println(a);
}
輸出
AA null 15
null null 0
public reflect.Person(java.lang.String,int)
public reflect.Person()
成員變量的反射set和get
private static void testFeild() {
//設(shè)置只有名字和年齡的對(duì)象
Person person = new Person("AA", 12);
try {
person.getClass().getFields();
//注意getDeclaredFields和 getFields的區(qū)別
Field[] fields = person.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
//打印所有的成員變量
System.out.println(fields[i]);
//設(shè)置字段可訪問
fields[i].setAccessible(true);
//設(shè)置對(duì)象的成員變量值
if (i == 0)
fields[i].set(person, "BB");
else if (i == 1) {
fields[i].set(person, 17);
} else if (i == 2) {
fields[i].set(person, "女");
}
//打印對(duì)象的成員變量值
System.out.println(fields[i].get(person));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(person);
}
輸出
public java.lang.String reflect.Person.name
BB
private int reflect.Person.age
int
17
private java.lang.String reflect.Person.sex
女
BB 女 17
成員方法的調(diào)用
private static void testMethod() {
Person person = new Person("AA", 12);
try {
Method method = person.getClass().getDeclaredMethod("setSex", String.class);
//私有成員變量必須要設(shè)置可訪問才能調(diào)用
method.setAccessible(true);
method.invoke(person, "男");
System.out.println(person);
Method method1 = person.getClass().getDeclaredMethod("sayPerson", String.class, int.class);
method1.invoke(person, "張三", 22);
} catch (Exception e) {
e.printStackTrace();
}
}
輸出
AA 男 12
張三 22
getDeclaredFields和 getFields的區(qū)別
private static void testAiffGetFeildsAndGetDeclaredFields() {
//設(shè)置只有名字和年齡的對(duì)象
Person person = new Person("AA", 12);
try {
person.getClass().getFields();
//注意getDeclaredFields和 getFields的區(qū)別
Field[] fields = person.getClass().getDeclaredFields();
Field[] fields2 = person.getClass().getFields();
for (int i = 0; i < fields.length; i++) {
System.out.println(fields[i]);
}
for (int i = 0; i < fields.length; i++) {
System.out.println(fields2[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
輸出
private java.lang.String reflect.Person.name
private int reflect.Person.age
private java.lang.String reflect.Person.sex
可以看到輸出的只有三個(gè),也就是說fields2 為空每窖;我們將Person的name字段更改為public帮掉,再進(jìn)行測試輸出如下:
public java.lang.String reflect.Person.name
private int reflect.Person.age
private java.lang.String reflect.Person.sex
public java.lang.String reflect.Person.name
輸出4個(gè)數(shù)據(jù),其中為name的數(shù)據(jù)顯示的兩條窒典,此兩條數(shù)據(jù)都是public類型蟆炊;
因此getFields獲取的數(shù)據(jù)為public字段,getDeclaredFields則獲取了所有的字段瀑志;
getEnclosingClass()涩搓、getEnclosingConstructor()、getEnclosingMethod()的區(qū)別劈猪;
都是與內(nèi)部類所在代碼位置相關(guān)的函數(shù)昧甘;
getEnclosingClass():獲取該類在那個(gè)類中定義;
getEnclosingConstructor():該類在哪個(gè)構(gòu)造函數(shù)中定義岸霹;
getEnclosingMethod():該類在哪個(gè)方法中定義的疾层;
invoke方法分析
@CallerSensitive
public Object invoke(Object obj, Object... args)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, obj, modifiers);
}
}
MethodAccessor ma = methodAccessor; // read volatile
if (ma == null) {
ma = acquireMethodAccessor();
}
return ma.invoke(obj, args);
}
override是什么呢,查看源碼是 method.setAccessible(true)設(shè)置該值,當(dāng)設(shè)置為true贡避,就可以忽略權(quán)限進(jìn)行訪問痛黎,這也就是為什么private要訪問必須設(shè)置此標(biāo)志的原因予弧;
Reflection.quickCheckMemberAccess(clazz, modifiers)代碼查看,確實(shí)是判斷是不是public成員的:
public static boolean quickCheckMemberAccess(Class<?> var0, int var1) {
return Modifier.isPublic(getClassAccessFlags(var0) & var1);
}
checkAccess(caller, clazz, obj, modifiers);是判斷不是public情況下湖饱,是否為該類(有可以子類的情況)掖蛤,再去判斷是不是protected,同時(shí)對(duì)該類進(jìn)行緩存,下一次調(diào)用此類就可以直接使用;
MethodAccessor是方法訪問對(duì)象接口井厌,在為null的情況下通過acquireMethodAccessor()函數(shù)實(shí)例化實(shí)現(xiàn)類蚓庭;最后調(diào)用實(shí)現(xiàn)類的invoke;acquireMethodAccessor()代碼如下:
private MethodAccessor acquireMethodAccessor() {
// First check to see if one has been created yet, and take it
// if so
MethodAccessor tmp = null;
if (root != null) tmp = root.getMethodAccessor();/*此處的root就是該方法對(duì)象*/
if (tmp != null) {
methodAccessor = tmp;
} else {
// Otherwise fabricate one and propagate it up to the root
tmp = reflectionFactory.newMethodAccessor(this);
setMethodAccessor(tmp);
}
return tmp;
}
該方法以工廠模式ReflectionFactory來獲得MethodAccessor 對(duì)象,
tmp = reflectionFactory.newMethodAccessor(this);
public MethodAccessor newMethodAccessor(Method var1) {
checkInitted();
if (noInflation && !ReflectUtil.isVMAnonymousClass(var1.getDeclaringClass())) {
return (new MethodAccessorGenerator()).generateMethod(var1.getDeclaringClass(), var1.getName(), var1.getParameterTypes(), var1.getReturnType(), var1.getExceptionTypes(), var1.getModifiers());
} else {
NativeMethodAccessorImpl var2 = new NativeMethodAccessorImpl(var1);
DelegatingMethodAccessorImpl var3 = new DelegatingMethodAccessorImpl(var2);
var2.setParent(var3);
return var3;
}
}
如果noInflation的屬性為true,則直接返回MethodAccessorGenerator創(chuàng)建的一個(gè)MethodAccessor仅仆。
否則返回DelegatingMethodAccessorImpl器赞,并將他與一個(gè)NativeMethodAccessorImpl互相引用。但DelegatingMethodAccessorImpl執(zhí)行invoke方法的時(shí)候又委托給NativeMethodAccessorImpl墓拜,因此最終是NativeMethodAccessorImpl調(diào)用了的invoke()港柜。NativeMethodAccessorImpl的invoke代碼如下:
public Object invoke(Object var1, Object[] var2) throws IllegalArgumentException, InvocationTargetException {
if (++this.numInvocations > ReflectionFactory.inflationThreshold() && !ReflectUtil.isVMAnonymousClass(this.method.getDeclaringClass())) {
MethodAccessorImpl var3 = (MethodAccessorImpl)(new MethodAccessorGenerator()).generateMethod(this.method.getDeclaringClass(), this.method.getName(), this.method.getParameterTypes(), this.method.getReturnType(), this.method.getExceptionTypes(), this.method.getModifiers());
this.parent.setDelegate(var3);
}
return invoke0(this.method, var1, var2);
}
其中numInvocations 是對(duì)該方法的調(diào)用次數(shù)的累積,若是numInvocations 計(jì)數(shù)調(diào)用次數(shù)超過ReflectionFactory.inflationThreshold()==15咳榜,則更改DelegatingMethodAccessorImpl的委托對(duì)象涌韩,由new MethodAccessorGenerator()生成的MethodAccessor對(duì)象代理,調(diào)用其invoke();
為什么要有這個(gè)15次的計(jì)數(shù)呢靶擦?這就是MethodAccessorGenerator()生成的MethodAccessor與NativeMethodAccessorImpl生成的MethodAccessor有區(qū)別奢啥;什么區(qū)別呢嘴拢?
可以看到MethodAccessorGenerator()是通過java直接生成的,NativeMethodAccessorImpl則是用native生成的赌结;
Java實(shí)現(xiàn)的版本在初始化時(shí)需要較多時(shí)間柬姚,但長久來說性能較好庄涡;native版本正好相反,啟動(dòng)時(shí)相對(duì)較快拿穴,但運(yùn)行時(shí)間長了之后速度就比不過Java版了忧风。這是HotSpot的優(yōu)化方式帶來的性能特性,同時(shí)也是許多虛擬機(jī)的共同點(diǎn):跨越native邊界會(huì)對(duì)優(yōu)化有阻礙作用腿宰,它就像個(gè)黑箱一樣讓虛擬機(jī)難以分析也將其內(nèi)聯(lián)缘厢,于是運(yùn)行時(shí)間長了之后反而是托管版本的代碼更快些。
為保持最好特性贴硫,前15次使用native夜畴,之后使用java版本删壮;
該方法學(xué)習(xí)根據(jù)源碼結(jié)合寂靜沙灘的JAVA深入研究——Method的Invoke方法]