2016-09-08 79 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"; 
      } 
     } 
    } 
}