Java uses reflection to get private construction methods, and reflection erase generic data type constraints

Source: Internet
Author: User
Tags reflection

/** Reflection gets private construction method run * Not recommended, corrupted program security, encapsulation * Violent private*/ Public classReflectDemo4 { Public Static voidMain (string[] args)throwsException {Class C=class.forname ("demo01. Person "); Constructor Con=c.getdeclaredconstructor (int.class, String.class); //constructor class, parent class AccessibleObject, defining Method Setaccessibile (Boolean flag)Con.setaccessible (true); Object obj=con.newinstance ("Lisi"));    System.out.println (obj); }}
 Packagedemo02;ImportJava.lang.reflect.Method;Importjava.util.ArrayList;/** Defines the collection class, the generic string * requires adding an integer type * reflection to the collection, gets the class file object of the collection ArrayList classes * Through the class file object, call the Add method * * To understand whether the reflection call method*/ Public classReflecttest { Public Static voidMain (string[] args)throwsException {ArrayList<String> array=NewArraylist<>(); Array.add (A); //reflection mode, gets the class file object of the collection ArrayListClass c=Array.getclass (); //get the method in the Arraylist.class file addMethod Method=c.getmethod ("Add", Object.class);        System.out.println (method); //To run the ArrayList method using invoke AddMethod.invoke (array,150); Method.invoke (Array,1500); Method.invoke (Array,15000);        SYSTEM.OUT.PRINTLN (array); //the enhanced for loop cannot traverse,    }}

Java uses reflection to get private construction methods, and reflection erase generic data type constraints

Related Article

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.