类的成员包含变量(Field),方法(Method),构造器(Constructor)
类定义
package Reflect; public class MyTest {
public int a;
public static int b;
public static final int c = 0;
private int d; public int sum(int a, int b, String c) {
return a + b;
} public int sub(int a, int b, String c) {
return a - b;
} MyTest() { } MyTest(int a, int b) { }
}
1.获取变量
package Reflect; import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier; public class Test {
public static void main(String[] args) {
System.out.println(MyTest.class);
final Class<?> clazz = MyTest.class;
System.out.println(clazz.getClass());
final Field[] fields = clazz.getDeclaredFields(); System.out.println("====print fields===");
for (final Field f : fields) {
System.out.print(f.getName() + "->");
System.out.print(f.getModifiers() + "->");
System.out.println(Modifier.toString(f.getModifiers()));
} }
输出:
class Reflect.MyTest
class java.lang.Class
====print fields===
a->1->public
b->9->public static
c->25->public static final
d->2->private
2.获取方法
package Reflect; import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier; public class Test {
public static void main(String[] args) {
System.out.println(MyTest.class);
final Class<?> clazz = MyTest.class;
System.out.println(clazz.getClass());
final Field[] fields = clazz.getDeclaredFields(); System.out.println("====print Method===");
final Method[] ms = clazz.getMethods();
for (final Method m : ms) {
System.out.println();
System.out.print(m.getName() + "==||");
System.out.print(m.getReturnType().getName() + "==||");
for (final Class o : m.getParameterTypes()) {
System.out.print(",==" + o.getName());
}
} }
}
输出:
====print Method===
sum==||int==||,==int,==int,==java.lang.String
sub==||int==||,==int,==int,==java.lang.String
wait==||void==||
wait==||void==||,==long,==int
wait==||void==||,==long
hashCode==||int==||
getClass==||java.lang.Class==||
equals==||boolean==||,==java.lang.Object
toString==||java.lang.String==||
notify==||void==||
notifyAll==||void==||
3.获取构造器
package Reflect; import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier; public class Test {
public static void main(String[] args) {
System.out.println(MyTest.class);
final Class<?> clazz = MyTest.class;
System.out.println(clazz.getClass()); System.out.println();
System.out.println("====print Constructor===");
final Constructor[] cs = clazz.getDeclaredConstructors();
for (final Constructor c : cs) {
System.out.println();
System.out.print(c.getName());
for (final Class o : c.getParameterTypes()) {
System.out.print(",==" + o.getName());
}
} }
} 输出:
====print Constructor===
Reflect.MyTest
Reflect.MyTest,==int,==int