获取类的结构信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.zss.reflact;


/**
* @author zss
*/
public class Cat {
public String name="asac";
public int age=0;
private String sex="娜娜";
int tall=15;
public void cry(){
System.out.println("HI");
}
void hello(){
System.out.println("NIAO");
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.zss.reflact;

import java.util.Arrays;

/**
* @author zss
*/
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
Class cla=Class.forName("com.zss.reflact.Cat");
//获得全类名
System.out.println(cla.getName());
//获得简单类名
System.out.println(cla.getSimpleName());
//获得所有公共的属性
System.out.println(Arrays.toString(cla.getFields()));
//获得本类所有的属性
System.out.println(Arrays.toString(cla.getDeclaredFields()));
//获得public方法
System.out.println(Arrays.toString(cla.getMethods()));
//所有方法
System.out.println(Arrays.toString(cla.getDeclaredMethods()));
//public构造器
System.out.println(Arrays.toString(cla.getConstructors()));
//所有构造器
System.out.println(Arrays.toString(cla.getDeclaredConstructors()));
//包名
System.out.println(cla.getPackage());
//父类
System.out.println(cla.getSuperclass());
//接口
System.out.println(Arrays.toString(cla.getInterfaces()));

}
}

image-20220321205903318

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.zss.reflact;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
* @author zss
*/
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
Class cla=Class.forName("com.zss.reflact.Cat");
//输出属性的修饰符,0代表默认,1代表public,2代表private,4代表protected,static是8,final是16,如果重复则会相加
//得到属性的类名信息
Field[] fields= cla.getFields();
for (Field f:fields){
System.out.println(f.getName()+f.getModifiers()+f.getType());
}



//方法的修饰符,返回方法修饰的对象
Method[] methods= cla.getMethods();
for (Method m:methods){
System.out.println(m.getName()+m.getModifiers()+m.getReturnType());
}

//构造器
Constructor []constructors= cla.getConstructors();
System.out.println(constructors[0].getName()+constructors[0].getModifiers()+ Arrays.toString(constructors[0].getTypeParameters()));
}
}

image-20220321211933358