標籤:cto pos 構造 val 建立 通過 stringbu close display
一、基礎知識
Class是泛型超類,封裝了類或介面運行時的狀態。Class是Java中的反射中心,可以在運行時尋找類的資訊。
class Solution { public static void main(String[] args) throws ClassNotFoundException { Class c = String.class;//通過類文字擷取 c = "Hello World".getClass();//通過getClass擷取 c = Class.forName("String");//通過forName擷取 c = Class.forName("String", false, Solution.class.getClassLoader()); }}View Code
二、類反射
import java.lang.reflect.Modifier;import java.lang.reflect.TypeVariable;import java.util.List;class Solution { public static void main(String[] args) { Class c = List.class; int modifier = 0;//修飾符 if (c.isInterface()) modifier = c.getModifiers() & Modifier.interfaceModifiers(); else modifier = c.getModifiers() & Modifier.classModifiers(); System.out.println(Modifier.toString(modifier)); TypeVariable<?>[] types = c.getTypeParameters();//泛型參數 for (TypeVariable t : types) System.out.println(t.getTypeName()); Class[] interfaces = c.getInterfaces();//實現介面 for (Class i : interfaces) System.out.println(i); }}View Code
三、欄位反射
Field可擷取類中的欄位資訊。
import java.lang.reflect.Field;class Solution { public static void main(String[] args) { Class<String> c = String.class; Field[] fields = c.getFields(); for (Field field : fields) System.out.println(field); //public static final java.util.Comparator java.lang.String.CASE_INSENSITIVE_ORDER }}View Code
四、方法反射
import java.lang.reflect.*;class Solution { static String getModifiers(Executable exec) { int modifier = exec.getModifiers(); if (exec instanceof Method) modifier &= Modifier.methodModifiers(); else if (exec instanceof Constructor) modifier &= Modifier.constructorModifiers(); return Modifier.toString(modifier); } static String getParameters(Executable exec) { Parameter[] parameters = exec.getParameters(); StringBuilder str = new StringBuilder(); for (Parameter parameter : parameters) str.append(parameter + " "); return str.toString(); } static String getExceptions(Executable exec) { StringBuilder str = new StringBuilder(); Class[] cs = exec.getExceptionTypes(); for (Class c : cs) str.append(c + " "); return str.toString(); } public static void main(String[] args) { Class<Integer> c = Integer.class; Method[] methods = c.getDeclaredMethods();//不包括從超類中繼承的方法 for (Method method : methods) { System.out.println(method.getName()); System.out.println(getModifiers(method)); System.out.println(getParameters(method)); System.out.println(getExceptions(method)); } }}View Code
五、反射對象建立
無參建構函式。
class MyClass { MyClass() { System.out.println("Constructor called"); }}class Solution { public static void main(String[] args) { Class<MyClass> c = MyClass.class; try { MyClass o = c.newInstance(); System.out.println(o); } catch (InstantiationException | IllegalAccessException exc) { exc.printStackTrace(); } }}View Code
帶參建構函式。
import java.lang.reflect.Constructor;class MyClass { MyClass(int i, String s) { System.out.println("Constructor called"); System.out.println(i); System.out.println(s); }}class Solution { public static void main(String[] args) { Class<MyClass> c = MyClass.class; try { Constructor<MyClass> cons = c.getConstructor(int.class, String.class);//只能調用public的方法 cons = c.getDeclaredConstructor(int.class, String.class);//可以調用本類聲明的所有方法 MyClass o = cons.newInstance(0, "Hello World"); System.out.println(o); } catch (Exception exc) { exc.printStackTrace(); } }}View Code
反射調用方法。
import java.lang.reflect.Method;class MyClass { public static void print(String s) { System.out.println(s); }}class Solution { public static void main(String[] args) { Class<MyClass> c = MyClass.class; try { MyClass o = c.newInstance(); Method method = c.getMethod("print", String.class); method.invoke(o, "Hello World"); } catch (Exception exc) { exc.printStackTrace(); } }}View Code
六、反射欄位訪問
import java.lang.reflect.Field;class MyClass { public String str = "Hello World";}class Solution { public static void main(String[] args) { Class<MyClass> c = MyClass.class; try { MyClass o = c.newInstance(); Field name = c.getField("str"); String value = (String) name.get(o); System.out.println(value); name.set(o, "Hello World"); value = (String) name.get(o); System.out.println(value); } catch (Exception exc) { exc.printStackTrace(); } }}View Code
訪問非可訪問欄位、方法和建構函式。
import java.lang.reflect.Field;class MyClass { private String str = "Hello World";}class Solution { public static void main(String[] args) { Class<MyClass> c = MyClass.class; try { MyClass o = c.newInstance(); Field str = c.getDeclaredField("str"); if (!str.isAccessible()) str.setAccessible(true); String value = (String) str.get(o); System.out.println(value); } catch (Exception exc) { System.out.println(exc.getMessage()); } }}View Code
七、數組反射
import java.lang.reflect.Array;class Solution { public static void main(String[] args) { try { int[] ar = (int[]) Array.newInstance(int.class, 10); for (int i = 0; i < 10; i++) Array.set(ar, i, i); for (int i = 0; i < 10; i++) System.out.println(Array.get(ar, i)); } catch (Exception exc) { System.out.println(exc.getMessage()); } }}View Code
擷取數組維度。
import java.lang.reflect.Array;class Solution { public static void main(String[] args) { try { int[][] arr = (int[][]) Array.newInstance(int.class, 5, 5); Class c = arr.getClass(); int i = 0; while (c.isArray()) { c = c.getComponentType(); i++; } System.out.println(i); } catch (Exception exc) { System.out.println(exc.getMessage()); } }}View Code
擴充數組。
import java.lang.reflect.Array;import java.util.Arrays;class Solution { static Object extend(Object oldArr) { int oldLength = Array.getLength(oldArr); int newLength = oldLength * 2; Class c = oldArr.getClass(); Object newArr = Array.newInstance(c.getComponentType(), newLength); System.arraycopy(oldArr, 0, newArr, 0, oldLength); return newArr; } public static void main(String[] args) { int[] arr = new int[5]; for (int i = 0; i < arr.length; i++) arr[i] = i; System.out.println(Arrays.toString(arr)); arr = (int[]) extend(arr); for (int i = 5; i < 10; i++) arr[i] = i; System.out.println(Arrays.toString(arr)); }}View Code
Java筆記:反射