Java初學者筆記六:反射
阿新 • • 發佈:2018-03-28
touch RR div getfields str span code new 獲取
Java反射基礎
零、基礎類代碼
import java.io.*;
import java.lang.reflect.*;
class father{
public String fName;
father(String name) {
this.fName = name;
}
public void show() throws Exception{
Runtime.getRuntime().exec("touch 2.txt");
}
}
class child extends father{
public int cAge;
child(int age,String name){
super(name);
this.cAge = age;
}
public void display() {
System.out.println("I am Child!");
}
}
一、根據對象和類獲取類
方法一 -> getClass()
對運行時候的對象調用getClass獲取其類對象
public class InvokeLearn{
public static void main(String[] args) throws Exception{
father f = new father("TOM");
child c = new child(5,"JIM");
String clsname = c.getClass().getName();//可以獲取類,然後getName返回類名字符串
System.out.println(clsname);
}
}
方法二 -> class屬性
對類本身調用class屬性
public class InvokeLearn{
public static void main(String[] args) throws Exception{
//Runtime.getRuntime().exec("touch 1.txt");
father f = new father("TOM");
child c = new child(5,"JIM");
String clsname = c.getClass().getName();
Class<child> clsname1 = child.class;
System.out.println(clsname1.getName());
}
}
方法三 -> Class.forName()
使用Class.forName()方法
public class InvokeLearn{
public static void main(String[] args) throws Exception{
//Runtime.getRuntime().exec("touch 1.txt");
father f = new father("TOM");
child c = new child(5,"JIM");
Class cls = Class.forName("father");
}
}
二、根據類獲取構造方法並創建實例
- 常用的幾個方法:
- getDeclaredConstructor()
- getDeclaredConstructors()
- getConstructors()
- getConstructor()
public class InvokeLearn{
public static void main(String[] args) throws Exception{
Class cls = Class.forName("father");
Constructor[] conArray= cls.getDeclaredConstructors();//所有構造方法
/*
* getConstructors() ->所有公有的構造方法
* getConstructors(null) -> 所有公有的無餐的構造方法
* getDeclaredConstructor(parameters_type) -> 私有的含參的構造方法,parameters_types是參數的類型
*/
//System.out.print(conArray.length);
Constructor newc = conArray[0];
Object obj = newc.newInstance("Tom");//調用構造方法創建實例
}
}
三、根據類獲取成員變量並使用
- 常用的幾個方法:
- getDeclaredField()
- getDeclaredFileds()
- getFields()
- getField()
public class InvokeLearn{
public static void main(String[] args) throws Exception{
Class cls = Class.forName("father");
Constructor[] conArray= cls.getDeclaredConstructors();//所有構造方法
Constructor newc = conArray[0];
Object obj = newc.newInstance("Tom");//創建實例
Field dis = cls.getDeclaredField("fName");//獲取屬性對象
dis.set(obj,"George");//設置屬性值
System.out.println(dis.get(obj));//獲取屬性值並打印
}
}
四、根據類獲取成員方法並使用
- 常用的幾個方法:
- getDeclaredMethod()
- getDeclaredMethods()
- getMethods()
- getMethod()
public class InvokeLearn{
public static void main(String[] args) throws Exception{
Class cls = Class.forName("father");
Constructor[] conArray= cls.getDeclaredConstructors();//所有構造方法
Constructor newc = conArray[0];
Object obj = newc.newInstance("JJJ");//創建實例
Method dis = cls.getDeclaredMethod("show",null);//獲取show方法
dis.invoke(obj, null);//調用show方法
}
}
Java初學者筆記六:反射