public class MyTest { private String string = "aaaa"; private void show(String msg){ Log.e("----", msg); } }
try { Class<?> aClass = Class.forName("com.youxila.memoryinfo.MyTest"); Field string = aClass.getDeclaredField("string"); string.setAccessible(true); Log.e("-----", string.get(new MyTest()).toString()); Method show = aClass.getDeclaredMethod("show", String.class); show.setAccessible(true); show.invoke(aClass.newInstance(),"heheheh"); } catch (Exception e) { e.printStackTrace(); }
1、取到类的字节码
Class<?> aClass = Class.forName("com.youxila.memoryinfo.MyTest");
2、取到该类中的方法或变量,在变量中,传入的是变量的变量名,在方法中传入的第一个是方法名,第二个是参数的类型.class,其中getDeclaredMethod及getDeclaredFile是可以取到private及protected修饰的变量及方法的。
Field string = aClass.getDeclaredField("string");
Method show = aClass.getDeclaredMethod("show", String.class);
3、调用setAccessible方法,否则在取private及protected修饰的变量及方法是会异常java.lang.IllegalAccessException: access to method denied
string.setAccessible(true);
show.setAccessible(true);4、得到目标类中的变量及方法
string.get(new MyTest()).toString()
show.invoke(aClass.newInstance(),"heheheh");