您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關java 中反射簡單使用示例,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
package reflect_test; public class Dog implements Animals { private int age =100; private String xstr="test..."; public int page = 100000; private Dog(String xstr) { this.xstr = xstr; } public Dog() { } public Dog(int age) { this.age = age; } @Override public String scrime(String str) { return str; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } private int getAddAge() { return age+=10; } public void getXstr() { System.out.println(xstr); } } -------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------- 測試類: package reflect_test; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.junit.Before; import org.junit.Test; public class TestDemo { Class<?> clazz= null; Class<?> interfa = null; Object obj = null; @Before public void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException { clazz = Class.forName("reflect_test.Dog"); interfa = Class.forName("reflect_test.Animals"); obj = clazz.newInstance(); } //調用非私有成員函數 @Test public void MethodTest() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Method m = clazz.getMethod("scrime", String.class); Object object = m.invoke(obj, "say....."); System.out.println(object); } //調用私有成員函數 @Test public void privateMethodTest() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Method m = clazz.getDeclaredMethod("getAddAge"); m.setAccessible(true); Object object = m.invoke(obj); System.out.println(object); } //獲取非私有構造函數 @Test public void getNotPrivateConstructor() throws Exception { Constructor<?> construct = clazz.getConstructor(int.class); Dog dog = (Dog)construct.newInstance(10); System.out.println("The age is : "+dog.getAge()); } //獲取私有構造函數 @Test public void getPrivateConstructor() throws Exception { //該出方法與非私有構造器區別getDeclaredConstructor Constructor<?> construct = clazz.getDeclaredConstructor(String.class); //獲得權限 construct.setAccessible(true); Dog dog = (Dog)construct.newInstance("1000"); dog.getXstr(); } //獲取非私有變量 @Test public void getField() throws Exception { Field f = clazz.getDeclaredField("age"); f.setAccessible(true); Object value = f.get(obj); System.out.println(value); } //獲取私有變量 @Test public void getPirvateField() throws Exception { Field f = clazz.getField("page"); Object value = f.get(obj); System.out.println(value); } }
關于“java 中反射簡單使用示例”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。