简体   繁体   中英

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

Is it possible to call powerof2() method ? I am getting java.lang.IllegalArgumentException: argument type mismatch for invoke

Reflection version:

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

Yes, things declared in the same top-level class can always access each other:

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

See Ideone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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