zoukankan      html  css  js  c++  java
  • 如何测试私有成员方法和变量

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

    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);
        }
    }

  • 相关阅读:
    vue基础04计算属性
    vue基础01条件渲染
    vue基础14vuex
    其他03动态拼接地址,使用本地的图片不显示
    其他05vue中ref
    HTML基础02CSS
    其他12es6...运算符
    其他11依赖注入
    其他07插槽
    其他06js类型判断
  • 原文地址:https://www.cnblogs.com/sunwei2012/p/1906217.html
Copyright © 2011-2022 走看看