android开发中反射也是常用到的方法,通过反射加载某个类中的方法并执行,下面就是对一般类中方法的反射总结:
//无参方法:public static BaseIntentHelper getInstance()
反射:Class<?> clazz = (Class<?>) Class.forName(className);//得到类实例
Method m = clazz.getMethod("getInstance", new Class[] {});//获取方法实例
BaseIntentHelper instance=(BaseIntentHelper)m.invoke(clazz,new Object[]{});//获取实例
//私有方法:private void jf(InputStream in)
//反射
public void test() throwsException{
Class clazz=Class.forName("Person");//得到person类
Method method=clazz.getDeclaredMethod("jf",InputStream.class);
method.setAccessible(true);//当构造方法是私有的,我们就进行暴力破解!!!
method.invoke(p,newFileInputStream("d:\\sc.txt"));
}
//带int型,String参数
//反射:
Method setMaxWidthMethod = clazz.getMethod(methodName//方法名, int.class,String.class);
setMaxWidthMethod.setAccessible(true);//如果为私有方法的话
setMaxWidthMethod.invoke(view, 9,"good");