调用私有方法static.私有类


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()方法?invoke = java.lang.IllegalArgumentException: argument type mismatch

是的,在同一个顶级类中声明的东西总是可以相互访问的:

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

看到Ideone

反射版本:

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

相关内容

最新更新