0%
Cat示范类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package com.zss.reflact;
public class Cat { public String name="asac"; private int he=10; public int age=0; int tall=15; public void cry(String name){ System.out.println("HI"+name); } public void hello(){ System.out.println("NIAO"); } @Override public String toString() { String sex = "娜娜"; return "Cat{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; }
public Cat(String name, int age, int tall) { this.name = name; this.age = age; this.tall = tall; } private Cat(String name){ this.name=name; }
public Cat() { } }
|
反射创建实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package com.zss.reflact;
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException;
public class Test { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class<?> cla= Class.forName("com.zss.reflact.Cat"); Object o=cla.newInstance(); System.out.println(o); Constructor<?> constructor=cla.getConstructor(String.class,int.class,int.class); constructor.newInstance("java",12,56); System.out.println(constructor);
Constructor<?> constructor1=cla.getDeclaredConstructor(String.class); constructor1.setAccessible(true); constructor1.newInstance("HAHA"); System.out.println(constructor1);
} }
|
反射访问类的成员
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package com.zss.reflact;
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException;
public class Test { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { Class<?> cla= Class.forName("com.zss.reflact.Cat"); Object o=cla.newInstance(); Field name=cla.getField("name"); name.set(o,"lili"); System.out.println(name.get(o));
Field he=cla.getDeclaredField("he"); he.setAccessible(true); System.out.println(he.get(o));
} }
|
反射访问方法
当然私有方法也可以爆破调用,其余用法与成员相同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package com.zss.reflact;
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
public class Test { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { Class<?> cla= Class.forName("com.zss.reflact.Cat"); Object o=cla.newInstance(); Method method=cla.getMethod("cry",String.class); method.invoke(o,"你好啊啊");
} }
|