簡體   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