標籤:變數 red extend isp 反射 exce stat 代碼 xtend
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初學者筆記六:反射