• 如何测试私有成员方法和变量


    先考虑它是否可以单独到一个类,再考虑使用反射

    class Stranger {

        public Stranger(final String name) {
            this.name = name;
        }

        private final String greet(final String hello) {
            return hello + name;
        }

        private String name = "";
    }

    public class PrivateTest {

        public static void main(String args[]) throws Exception {

            Stranger testObj = new Stranger("Walter");
            Class testClass = testObj.getClass();
            // get private property
            Field field = testClass.getDeclaredField("name");
            // Make the field accessible
            field.setAccessible(true);
            
            // get private method
            Class[] typeParams = new Class[] { String.class };
            Method method = testClass.getDeclaredMethod("greet", typeParams);
            // Make the method accessible
            method.setAccessible(true);
            // execute the method
            Object objParams[] = { "hello, " };
            String greet = (String)method.invoke(testObj, objParams);
            
            System.out.println(greet);
        }
    }

  • 相关阅读:
    java——base64 加密和解密
    BASE64Encoded() 方法报错说方法未定义
    java 实现HTTP连接(HTTPClient)
    如何关闭一些烦人的弹窗(总结)
    IDEA
    6、git和github
    5、预测和鉴定miRNA的靶基因
    4、在线blast比对结果解析(保守结构域)
    ASE分析
    3、Linux下配置Java环境
  • 原文地址:https://www.cnblogs.com/sunwei2012/p/1906217.html
Copyright © 2020-2023  润新知