Examples of common Java reflection methods and java reflection examples

Source: Internet
Author: User

Examples of common Java reflection methods and java reflection examples

<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 the object Class cls1 = Class. forName ("Point"); Constructor con1 = cls1.getConstructor (int. class, int. class); Point p1 = (Point) con1.newInstance (5, 6); p1.printPoint (); // use the second method to create an object Class cls2 = Point. class; Point p2 = (Point) cls2.newInstance (); // No parameter constructor p2.printPoint (); // use the third method to create the object Class cls3 = p1.getClass (); // use the setX Method of the p1 object to change the x value to 10 Method m1 = cls3.getMethod ("setX", int. class); m1.invoke (p1, 10); p1.printPoint ();/** Note: * getDeclaredConstructor can return the constructor of the specified parameter, * getConstructor can only return the public Constructor of the specified parameter. **/Constructor con2 = cls3.getDeclaredConstructor (int. class); // accessiblecon2.setAccessible (true) must be set for accessing private variables and functions; Point p4 = (Point) con2.newInstance (3); p4.printPoint (); // Field f1 = cls3.getField ("y"); // errorField f1 = cls3.getDeclaredField ("y"); f1.setAccessible (true); // obtain the y value of p1 System. out. println (f1.get (p1 ));}}


 

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.