The Java reflection mechanism calls the construction method of the private type

Source: Internet
Author: User

Singleton class:

 PackageSingleton; Public classSingletontest {//Private Construction Methods    Privatesingletontest () {System.out.println ("No Parameter---construction----"); }    //Private Construction Methods    PrivateSingletontest (String a) {System.out.println ("Parameter---Constructed----parameter value:" +a); }    //define a variable of a private type    Private Static volatileSingletontest instance; //define a static common method     Public Staticsingletontest getinstance () {if(Instance = =NULL){            synchronized(Singletontest.class){                if(Instance = =NULL){                    return Newsingletontest (); }            }        }        returninstance; }}

Test Call class:

 Packagereflect;ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.Method;ImportSingleton. Singletontest; Public classReflectdemo { Public Static voidMain (string[] args)throwsexception{Class clazz= Singletontest.class; /*The following call to the non-parametric, private constructor*/Constructor C0=Clazz.getdeclaredconstructor (); C0.setaccessible (true); Singletontest PO=(singletontest) c0.newinstance (); System.out.println ("No parameter constructor \ t" +PO); /*The following call to a private constructor with parameters*/Constructor C1=clazz.getdeclaredconstructor (NewClass[]{string.class}); C1.setaccessible (true); Singletontest P1= (singletontest) c1.newinstance (Newobject[]{"I am the parameter value"}); System.out.println ("Argument constructor \ T" +p1); }}

Output Result:

Construction----WITHOUT parameters---
No parameter constructor [email protected]
Parameters---Constructed----parameter values: I am the parameter value
Parametric constructors [email protected]

The Java reflection mechanism calls the construction method of the private type

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.