package javaweb.reflect; public class Reflect { /** * @param args * @throws ClassNotFoundException * 反射:加载类,获得类的字节码 */ public static void main(String[] args) throws ClassNotFoundException { //加载类方法1: Class c1 = Class.forName("javaweb.reflect.Person"); //2 Class c2 = new Person().getClass(); //3 Class c3 = Person.class; } }
常用方法:
1 //public 2 Constructor getConstructor() 3 Method getMethod() 4 Field getField() 5 //private 6 Constructor getDeclaredConstructor() 7 Method getDeclaredMethod() 8 Field getDeclaredField() 9 10 c.setAccessible(true);//暴力反射
反射类的构造函数:
1 public void test(){ 2 Class c = Class.forName("javaweb.reflect.Person"); 3 Constructor<T> cs = c.getConstructor(String.class); 4 Person p = cs.newInstance("xxx"); 5 }
反射类的方法:
1 public void test() throws ClassNotFoundException { 2 Person p = new Person(); 3 Class c = Class.forName("javaweb.reflect.Person"); 4 Method method = c.getMethod("funName", null); 5 method.invoke(p,null); 6 }
反射类的字段:
1 package javaweb.reflect; 2 3 import java.lang.reflect.Field; 4 5 public class Reflect { 6 7 /** 8 * @param args 9 * @throws ClassNotFoundException 10 * 反射:加载类,获得类的字节码 11 * @throws SecurityException 12 * @throws NoSuchFieldException 13 * @throws IllegalAccessException 14 * @throws IllegalArgumentException 15 */ 16 public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{ 17 Person p = new Person(); 18 Class<?> c = Class.forName("javaweb.reflect.Person"); 19 Field f = c.getField("name"); 20 String name =(String) f.get(p); 21 System.out.println(name); 22 23 //打印出字段name的类型 24 Class<?> type = f.getType(); 25 System.out.println(type); 26 } 27 }