Post on Java internal class (class in class) Reflection instantiation

Source: Internet
Author: User

Today, I was modifying the MongoDB Java driver and suddenly found that my foo class could not create an instance.

Later, we found that foo is an internal class, so it cannot be reflected directly to create its instance,CodeThe prototype is as follows:

 1   Public   Final   Class  Unittests  2   {  3   @ Test  4           Public   Void Footest () Throws Illegalaccessexception, instantiationexception, nosuchfieldexception  5   {  6 Class C = Foo. Class  ;  7 Foo OBJ = (FOO) C. newinstance ();  8 Field Fi = C. getfield ("name" );  9    10 Fi. Set (OBJ, "foo: Your name" ); 11    12   System. Out. println (obj. Name );  13   }  14           15           Public   Final   Class  Foo  16   {  17                   Public  String name;  18  }  19 }

Go to the group and ask you about Java.
However, I found that some examples of the MongoDB driver can be reflected. After careful comparison, I found that "the static modifier needs to be added to the internal class", that is:

 
Public Static Final ClassFoo

For the role of static keywords in Java, see: http://www.2cto.com/kf/201109/104884.html

Thank you for your reference!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.