繁体   English   中英

调用私有方法static.private类

[英]Call private method static.private class

public class Test {
    public static void main(String[] args) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int num = Integer.parseInt(br.readLine().trim());
            Object o;


        Method[] methods = Inner.class.getEnclosingClass().getMethods();
        for(int i=0;i<methods.length;i++) {
            System.out.println(methods[i].invoke(new Solution(),8));
        }
            // Call powerof2 method here

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class Inner {
        private class Private {
            private String powerof2(int num) {
                return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2";
            }
        }
    }
}

是否可以调用powerof2()方法? 我正在获取java.lang.IllegalArgumentException: argument type mismatch以进行invoke

反射版:

public class Test {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchMethodException {

        Class<?> privateCls = Inner.class.getDeclaredClasses()[0];


        Method powerMethod = privateCls.getDeclaredMethod("powerof2", int.class);

        powerMethod.setAccessible(true);
        Constructor<?> constructor = privateCls.getDeclaredConstructors()[0];
        constructor.setAccessible(true);
        Object instance = constructor.newInstance(new Inner());

        System.out.println(powerMethod.invoke(instance, 2));

    }

    static class Inner {
        private class Private {
            private String powerof2(int num) {
                return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2";
            }
        }
    }
}

是的,在同一顶级类中声明的内容始终可以相互访问:

public class Test {
    public static void main(String[] args) throws Exception {
        Inner i = new Inner(); // Create an instance of Inner
        Inner.Private p = i.new Private(); // Create an instance of Private through
                                           // the instance of Inner, this is needed since
                                           // Private is not a static class.

        System.out.println(p.powerof2(2)); // Call the method
    }

    static class Inner {
        private class Private {
            private String powerof2(int num) {
                return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2";
            }
        }
    }
}

Ideon

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM