zoukankan      html  css  js  c++  java
  • java如何禁掉反射

    SecurityManager

    有一个checkMemberAccess这个方法可以阻止利用反射;
    如:

    SecurityManager sm = new SecurityManager();
    sm.checkMemberAccess(Test.class, Member.PUBLIC);

    前面一个为CLASS,后面需要填一个INT值,Member.PUBLIC 代表可以访问,
    如果是PUBLIC,反射可以执行,DECLARED,反射运行时,会报错。

    SecurityManager另外一个例子:
    package com.jd.basic.pk.manager;
    
    import java.lang.reflect.Field;
    import java.security.Permission;
    
    public class UseReflection {
        static {
            try {
                System.setSecurityManager(new MySecurityManager());
            } catch (SecurityException se) {
                System.out.println("SecurityManager already set!");
            }
    
        }
    
        public static void main(String args[]) {
            Object prey = new Prey();
            try {
                Field pf = prey.getClass().getDeclaredField("privateString");
                pf.setAccessible(true);
                pf.set(prey, "Aminur test");
                System.out.println(pf.get(prey));
            } catch (Exception e) {
                System.err.println("Caught exception " + e.toString());
            }
    
        }
    }
    
    class Prey {
        @SuppressWarnings("unused")
        private String privateString = "privateValue";
    }
    
    class MySecurityManager extends SecurityManager {
        public void checkPermission(Permission perm) {
            if (perm.getName().equals("suppressAccessChecks")) {
                throw new SecurityException("Can not change the permission dude.!");
            }
        }
    }

    参考:http://bbs.csdn.net/topics/390472034

  • 相关阅读:
    android SQLite使用
    蓝牙从搜索到成功配对的全过程
    vscode 开发.net core 从安装到部署 教程详解
    ServiceStack 简单服务搭建
    MongoDB 安装配置
    request.url 端口 错误
    Python 之 hello world
    .NET DateTime 源码学习
    Parallel.For 平行算法 使用
    Thread.Join 和 Task.Wait 方法
  • 原文地址:https://www.cnblogs.com/olmlo/p/5488432.html
Copyright © 2011-2022 走看看