2016-09-08 49 views
-1
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 mismatchinvoke调用私有方法static.private类

+1

当你尝试时发生了什么? – bradimus

+0

有没有反思? –

+0

@bradimus我更新了我的问题 – manish

回答

1

是的,在同一个顶层类中声明的东西总是能够互相访问:

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

+0

cn我如何使用反射和同时吻合来做同样的事情? – manish

+0

@manish你为什么要使用反射?它通常不是很友善? –

+0

好吧,你提到的代码背后的逻辑是什么,我的意思是我想知道更多详细信息 – manish

1

反思版本:

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