Examples of common methods for Java reflection

Source: Internet
Author: User

<pre name= "code" class= "java" >import java.lang.reflect.constructor;import Java.lang.reflect.field;import Java.lang.reflect.method;class point{int x;private int y;public Point () {x = 1;y = 2;} public void SetX (int x) {this.x = x;} public void sety (int y) {this.y = y;} private point (int x) {this (); this.x = x;} public point (int x, int y) {super (); this.x = X;this.y = y;} public void Printpoint () {System.out.println ("x =" + x + ", y =" + y);}} public class ReflectTest2 {public static void main (string[] args) throws Exception {//Use the first method to create an object class CLS1 = Class.fornam E ("point"); Constructor Con1 = Cls1.getconstructor (Int.class,int.class); Point P1 = (point) con1.newinstance (5,6);p 1.printPoint ();//Use the second method to create the object class CLS2 = Point.class; Point P2 = (point) cls2.newinstance ();//non-parametric constructor p2.printpoint ();//Use the third method to create the object class CLS3 = P1.getclass ();// Use the SetX method of the P1 object to modify the X value to 10Method m1 = Cls3.getmethod ("SetX", Int.class), M1.invoke (p1);p 1.printPoint (); */* NOTE: * Getdeclaredconstructor can return the constructor for the specified argument, while the GetconstrucTor can only be put back to the constructor of public for the specified parameter * */constructor con2 = cls3.getdeclaredconstructor (Int.class);//access to private variables, The function needs to be set to accessiblecon2.setaccessible (true); Point P4 = (point) con2.newinstance (3);p 4.printPoint (),//field f1 = Cls3.getfield ("y");//errorfield f1 = Cls3.getdeclaredfield ("Y"); F1.setaccessible (true);//Get P1 y value System.out.println (F1.get (p1));}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Examples of common methods for Java reflection

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.