2011-09-19 11 views
17

final variable passed to anonymous class via constructor में, जॉन स्कीट ने उल्लेख किया कि अज्ञात वर्ग उदाहरण को एक ऑटो-जेनरेटेड कन्स्ट्रक्टर के माध्यम से चर पारित किया जाता है। क्यों मैं निर्माता उस मामले में प्रतिबिंब का उपयोग को देखने के लिए सक्षम नहीं होगा:गुमनाम वर्गों के लिए अंतिम चर को पास करना

public static void main(String... args) throws InterruptedException { 
final int x = 100; 
new Thread() { 
    public void run() { 
     System.out.println(x);  
     for (Constructor<?> cons : this.getClass() 
       .getDeclaredConstructors()) { 
      StringBuilder str = new StringBuilder(); 
      str.append("constructor : ").append(cons.getName()) 
        .append("("); 
      for (Class<?> param : cons.getParameterTypes()) { 
       str.append(param.getSimpleName()).append(", "); 
      } 
      if (str.charAt(str.length() - 1) == ' ') { 
       str.replace(str.length() - 2, str.length(), ")"); 
      } else 
       str.append(')'); 
      System.out.println(str); 
     } 
    } 

}.start(); 
Thread.sleep(2000); 

}

उत्पादन होता है:

100 
constructor : A$1() 

उत्तर

16

यहाँ अपने कार्यक्रम अपने सिस्टम पर बाहर प्रिंट है:

100 
constructor : A$1() 

तो निर्माता है । हालांकि, यह पैरामीटर रहित है। डिस्सेप्लिब्स को देखने से, क्या होता है कि संकलक यह बताता है कि इसे x से run() पास करने की आवश्यकता नहीं है क्योंकि इसका मूल्य संकलन समय पर जाना जाता है।

अगर मैं कोड इसलिए की तरह बदलने के लिए:

public class A { 

    public static void test(final int x) throws InterruptedException { 
     new Thread() { 
      public void run() { 
       System.out.println(x); 
       for (Constructor<?> cons : this.getClass() 
         .getDeclaredConstructors()) { 
        StringBuilder str = new StringBuilder(); 
        str.append("constructor : ").append(cons.getName()) 
          .append("("); 
        for (Class<?> param : cons.getParameterTypes()) { 
         str.append(param.getSimpleName()).append(", "); 
        } 
        if (str.charAt(str.length() - 1) == ' ') { 
         str.replace(str.length() - 2, str.length(), ")"); 
        } else 
         str.append(')'); 
        System.out.println(str); 
       } 
      } 

     }.start(); 
     Thread.sleep(2000); 
     } 

    public static void main(String[] args) throws InterruptedException { 
     test(100); 
    } 

} 

निर्माता उत्पन्न हो जाता है कि अब है:

constructor : A$1(int) 

एकमात्र तर्क x का मूल्य है।

27

इस मामले में, यह क्योंकि 100 एक निरंतर है। यह आपकी कक्षा में बेक्ड हो जाता है।

आप x को बदलते हैं होने के लिए:

final int x = args.length; 

... तो आप उत्पादन में Test$1(int) देखेंगे। (। ऐसा इसके बावजूद यह स्पष्ट रूप से घोषित नहीं किया जा रहा और हाँ, अधिक चरों पर कब्जा निर्माता पैरामीटर जोड़ देता है।)

+1

@ बोहेमियन: यह देखते हुए कि मुझे प्रश्न की उत्पत्ति पता है, मुझे लगता है कि यह है :) –

संबंधित मुद्दे