Java record-85-Example of Reflection API usage advanced
To use reflection, you must first obtain the Class object corresponding to the Class or object to be processed. The following three methods are commonly used to obtain the Class object corresponding to a Class or an object: 1. use the static method forName and Class of the Class. forName ("java. lang. string "); 2. use. class Syntax: String. class; 3. use the getClass () method of the object: String s = "aa"; Class <?> Clazz = s. getClass (); if you want to generate an object through the class constructor without parameters, there are two methods: 1. obtain the Class Object first, and then generate it directly using the newInstance () method of the Class object; 2. first obtain the Class object, then obtain the corresponding Constructor object through this object, and then generate it using the newInstance () method of this Constructor object;
Public class ReflectTester {// This method implements the Object copy operation public Object copy (object Object) throws Exception {Class <?> ClassType = object. getClass (); // System. out. println (classType); // class my. reflect. customer Object obj = classType. newInstance (); System. out. println (obj); // my. reflect. customer @ c17164 // The following two lines of code are equivalent to the classType above. newInstance (); Constructor cons = classType. getConstructor (new Class [] {}); Object obj2 = cons. newInstance (new Object [] {}); System. out. println (obj2); // my. reflect. customer @ 1fb8ee3 // produce the object Constructor cons1 = classType by using the Construction Method with parameters. getConstructor (new Class [] {String. class, int. class}); Object obj3 = cons1.newInstance (new Object [] {"hello", 23}); System. out. println (obj3); // my. reflect. customer @ 61de33 return null;} public static void main (String [] args) throws Exception {ReflectTester test = new ReflectTester (); test. copy (new Customer () ;}} class Customer {private long id; private String name; private int age; public Customer () {} public Customer (String name, int age) {this. name = name; this. age = age;} public long getId () {return id;} public void setId (long id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}