----------- android培訓、java培訓、java學習型技術博客、期待與您交流! ------------
學習筆記-反射
package Reflect;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
public class ReflectTest {
/**
* 使用放射的方式
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
/**
true
true
false
true
false
true
false
true
*/
/**
* 初步反射
*/
String str1 = "abc";
Class cls1 = str1.getClass();
Class cls2 = String.class;
Class cls3 = Class.forName("java.lang.String");
System.out.println(cls1 == cls2);
System.out.println(cls1 == cls3);
System.out.println(cls1.isPrimitive());
System.out.println(int.class.isPrimitive());
System.out.println(int.class == Integer.class);
System.out.println(int.class == Integer.TYPE);
System.out.println(int[].class.isPrimitive());
System.out.println(int[].class.isArray());
/**
* 反射構造方法 Constructor類
*/
//Class<?>... parameterTypes throws NoSuchMethodException, SecurityException
//Constructor<String>
//使用String的這份字節碼得到構造方法
//第一個StringBuffer是表示選擇哪個構造方法
Constructor c1 = String.class.getConstructor(StringBuffer.class);
//用這個方法是傳一個StringBuffer對象進去
// Object java.lang.reflect.Constructor.newInstance 返回一個對象
//強轉的原因:c1本來是一個個StringBuffer類型的對象,但是卻傳了一個String類型的變量
//所以需要強轉
String str2 = (String) c1.newInstance(new StringBuffer("abc"));
System.out.println(str2.charAt(2));
/**
* 反射方法 Method類
*/
//對點進行反射
ReflectPoint p1 = new ReflectPoint(3, 5);
//只是得到y這個對象身上的字節碼
//fy只是一個變量
//getField(),只能得到共有的,可見的
Field fy = p1.getClass().getField("y");
//fy不是對象身上的變量,而是類身上,要用它去取某個對象上對應的值
System.out.println(fy.get(p1));
//x爲私有的,不能直接反射得到
//通過暴力反射得到x的值
Field fx = p1.getClass().getDeclaredField("x");
fx.setAccessible(true);
//fx不是對象身上的變量,而是類身上,要用它去取某個對象上對應的值
System.out.println(fx.get(p1));
/**
* 反射字段 Field類
*/
changStringValue(p1);
System.out.println(p1);
//getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
Method methodCharAt = String.class.getMethod("charAt", int.class);
//.Method.invoke(Object obj, Object... args)
//invoke調用,祈求,喚起,藉助
//司機把車停下了
//真正實現停車這個動作的是車,不是人。停車這個動作是車實現的
//關門:人只是發送一個關的信號
//真正實現關門這個動作是門中的方法:關門
//靜態方法不需要對象
//如果傳遞給Method對象的invoke()方法的一個參數爲Null,
//這有着什麼樣的意義呢?說明該Mehtod對象應用的是一個靜
//態方法。
System.out.println(methodCharAt.invoke(str1, 1));
//new Object[]{new String("abc"),1};
//jdk1.4下面的放射方法
//Object... args new一個對象,傳一個int型的參數=2
System.out.println(methodCharAt.invoke(str1, new Object[]{2}));
//使用通常使用的方法
//TestArgument.main(new String[]{"111","222","333"});
/**
* 用反射方式執行某個類中的mian方法
*/
String startingClassName = args[0];
Method mainMethod = Class.forName(startingClassName).getMethod("main", String[].class);
mainMethod.invoke(null, new Object[] {new String[]{"1111","2222","3333"}});
mainMethod.invoke(null, (Object)new String[]{"1111","2222","3333"});
/**
* 數組與Object的關係及其與反射類型
*/
int [] a1 = new int[]{1,2,3};
int [] a2 = new int[4];
int [] [] a3 = new int[2][3];
String [] a4 = new String[]{"a","b","c"};
System.out.println(a1.getClass() == a2.getClass());
//不兼容的操作數類型類
//System.out.println(a1.getClass() == a4.getClass());
//System.out.println(a1.getClass() == a3.getClass());
//System.out.println(a1==a3);
System.out.println(a1.getClass().getName());
//他們的父類都是 java.lang.Object
System.out.println(a1.getClass().getSuperclass().getName());
System.out.println(a4.getClass().getSuperclass().getName());
Object aObj1 = a1;
Object aObj2 = a4;
//Object[] aObj3 = a1;
Object[] aObj4 = a3;
Object[] aObj5 = a4;
System.out.println(a1);
//@c9d92c hashcode值
System.out.println(a4);
//整數數組[[I@1e4f7c2]
System.out.println(Arrays.asList(a1));
//字符就成爲[a, b, c]
System.out.println(Arrays.asList(a4));
/**
* 數組的反射應用
*/
printObject(a4);
printObject("xyz");
}
/**
* 數組的反射應用
* @param obj
*/
private static void printObject(Object obj) {
Class clazz = obj.getClass();
if(clazz.isArray()){
int len =Array.getLength(obj);
for(int x = 0;x<len;x++){
System.out.println(Array.get(obj, x));
}
}else{
System.out.println(obj);
}
}
/**
* Field類
* @param obj
* @throws Exception
*/
private static void changStringValue(Object obj) throws Exception {
Field[] fields = obj.getClass().getFields();
for(Field field:fields){
//if(field.getType().equals(String.class)){}
//字節碼用 ==
//因爲是同一份字節碼,所以使用==號
if(field.getType() == String.class){
String oldValue = (String) field.get(obj);
//把字段中value中的的b替換成a
String newValue = oldValue.replace("b", "a");
field.set(obj, newValue);
}
}
}
}
class TestArgument{
public static void main(String [] args) throws Exception
{
for(String arg:args){
System.out.println(arg);
}
}
}
字段反射用到的類
package Reflect;
//字段的反射
public class ReflectPoint {
private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "ballsss";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="
+ str3 + "]";
}
/**
* 作用:
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}