Java reflection mechanism: four methods for getting Class objects
1 package com. ljq. test;
2
3 import java. lang. reflect. Field;
4 import java. util. Currency;
5
6 /**
7 * four Java reflection methods for getting Class objects
8 *
9 * @ author jiqinlin
10 *
11 */
12 public class GetClassTest {
13 public static void main (String [] args ){
14 new GetClassTest (). checkClass ();
15}
16
17 public boolean checkClass (){
18 try {
19 System. out. println ("1. Get the object through the class itself ");
20 Class clazz = this. getClass ();
21 System. out. println (clazz. getName ());
22 System. out. println ("================= ");
23
24 System. out. println ("2. Obtain the parent class object through the subclass instance ");
25 Customer customer = new Customer ();
26 clazz = customer. getClass ();
27 System. out. println (clazz. getSuperclass (). getName ());
28 System. out. println ("================= ");
29
30 System. out. println ("3. Get the object through class name. class ");
31 Class forClass = com. ljq. test. GetClassTest. class;
32 System. out. println (forClass. getName ());
33 System. out. println ("================= ");
34
35 System. out. println ("4. Get the object through the class name string ");
36 Class forName = Class. forName ("com. ljq. test. GetClassTest ");
37 System. out. println (forName. getName ());
38 System. out. println ("=============== ");
39
40} catch (Exception e ){
41 return false;
42}
43 return true;
44}
45}
Customer class
1 package com.ljq.test;
2
3 public class Customer {
4 private Long id;
5 private String name;
6 private int age;
7
8 public Customer() {
9 }
10
11 public Customer(String name, int age) {
12 this.name = name;
13 this.age = age;
14 }
15
16 public Long getId() {
17 return id;
18 }
19
20 public void setId(Long id) {
21 this.id = id;
22 }
23
24 public String getName() {
25 return name;
26 }
27
28 public void setName(String name) {
29 this.name = name;
30 }
31
32 public int getAge() {
33 return age;
34 }
35
36 public void setAge(int age) {
37 this.age = age;
38 }
39 }