C# 反射

        public static void CallPrivateMethod(object instance, string name, params object[] param)
        {
            BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;
            Type type = instance.GetType();
            MethodInfo method = type.GetMethod(name, flag);
            method.Invoke(instance, param);
        }

转自 https://segmentfault.com/q/1010000007608935?_ea=1398469

            var request = (HttpWebRequest)WebRequest.Create("https://");

            CallPrivateMethod(request, "SetSpecialHeaders", "AAAAAAAA", DateTime.Now.ToString("R"));

 

    //获得字节码文件对象
        Class  c =  Class.forName("reflect.Demo");
        //获取到带参数的构造对象
        Constructor  d =  c.getConstructor(int.class);
        //通过Class里的newInstance() 创建对象
        //Demo d = (Demo)c.newInstance();

        Demo  dd= (Demo) d.newInstance(1); 
        //获取到方法的对象
        Method  m = c.getMethod("print",String.class);
        Method m1 = c.getDeclaredMethod("show",int.class);
        //调用即可
        m.invoke(dd,"hh");
        //私有的设置显示即可
        m1.setAccessible(true);
        m1.invoke(dd, 1);


    }

}
class Demo {
    public Demo(){}
    public Demo(int x) {
    }
    private void show(int a) {
        System.out.println(1111);
    }
    public void print(String str ){
        System.out.println("Hello "+str);
    }
}

原文链接:https://blog.csdn.net/qq_35257397/article/details/52746105

 

posted @ 2019-11-24 14:43  enych  阅读(192)  评论(0编辑  收藏  举报