本文章主要介绍了Java通过反射机制获取Class对象,具有不错的的参考价值,希望对您有所帮助,如解说有误或未考虑完全的地方,请您留言指出,谢谢!
Java反射机制四种获取Class对象的方法
1 package com.ljq.test;
2
3 import java.lang.reflect.Field;
4 import java.util.Currency;
5
6 /**
7 * Java反射机制四种获取Class对象的方法
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、通过类本身获得对象 " );
20 Class clazz = this .getClass();
21 System.out.println(clazz.getName());
22 System.out.println( " ============== " );
23
24 System.out.println( " 2、通过子类的实例获得父类对象 " );
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、通过类名.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、通过类名的字符串获取对象 " );
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类
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 }
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/228193.html