<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