Java Reflection (Java.lang.reflect)---Common singleton mode uniqueness problem

Source: Internet
Author: User

1. Ordinary full-Han style, a hungry man style

Package Org.bighead.test2;public class Testprivate {private String str = "Strprivate";p rivate static final testprivate TES Tprivate = new Testprivate ();//Full-han, a hungry man-style private testprivate () {super (); System.out.println (str);} Public Testprivate getinstance () {return testprivate;} public void Toprint () {System.out.println ("private construct-open method-Single instance");}}

Reflection creates an instance, invokes a method (an instance is accessible)

Package Org.bighead.test2;import Java.lang.reflect.constructor;import Java.lang.reflect.InvocationTargetException ;p Ublic class testdefaultsub  {public static void main (string[] args) {class<testprivate> clazz = Testprivate.class;try {constructor<?> Constructor = Clazz.getdeclaredconstructor (); constructor.setaccessible (true); testprivate TP = (testprivate) constructor.newinstance (); Tp.toprint ();} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch (Instantiationexception E1) {e1.printstacktrace ();} catch (Illegalaccessexception E1) {E1.printstacktrace ();} catch (InvocationTargetException E1) {e1.printstacktrace ();}}}

2. Concurrency can also affect

Java Reflection (Java.lang.reflect)---Common singleton mode uniqueness problem

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.