详细解释请点转载地址:http://www.cnblogs.com/lzq198754/p/5780331.html
1.获得类的完整的包名和类名:
TestReflect testReflect =
new
TestReflect();
System.out.println(testReflect.getClass().getName());
2.实例化Class对象的三种方法:
Class<?> class1 = Class.forName(
"net.xsoftlab.baike.TestReflect"
);
Class<?>
class2 =
new
TestReflect().getClass();
Class<?>
class3 = TestReflect.
class
;
3.获取一个类的父类和实现的接口:
// 实例化对象
Class<?> clazz = Class.forName(
"net.xsoftlab.baike.TestReflect"
);
// 取得父类
Class<?> parentClass = clazz.getSuperclass();
System.out.println(
"clazz的父类为:"
+ parentClass.getName());
// clazz的父类为: java.lang.Object
// 获取所有的接口
Class<?> intes[] = clazz.getInterfaces();
System.out.println(
"clazz实现的接口有:"
);
for
(
int
i =
0
; i < intes.length; i++) {
System.out.println((i +
1
) +
":"
+ intes[i].getName());
}
4.获得类中的所有的构造函数:
Constructor<?> cons[] = class1.getConstructors();
// 查看每个构造方法需要的参数
for
(
int
i =
0
; i < cons.length; i++) {
Class<?> clazzs[] = cons[i].getParameterTypes();
System.out.print(
"cons["
+ i +
"] ("
);
for
(
int
j =
0
; j < clazzs.length; j++) {
if
(j == clazzs.length -
1
)
System.out.print(clazzs[j].getName());
else
System.out.print(clazzs[j].getName() +
","
);
}
System.out.println(
")"
);
}
5.获得某个类的全部属性:
Class<?> clazz = Class.forName(
"net.xsoftlab.baike.TestReflect"
);
System.out.println(
"===============本类属性==============="
);
// 取得本类的全部属性
Field[] field = clazz.getDeclaredFields();
for
(
int
i =
0
; i < field.length; i++) {
// 权限修饰符
int
mo = field[i].getModifiers();
String priv = Modifier.toString(mo);
// 属性类型
Class<?> type = field[i].getType();
System.out.println(priv +
" "
+ type.getName() +
" "
+ field[i].getName() +
";"
);
}
System.out.println(
"==========实现的接口或者父类的属性=========="
);
// 取得实现的接口或者父类的属性
Field[] filed1 = clazz.getFields();
for
(
int
j =
0
; j < filed1.length; j++) {
// 权限修饰符
int
mo = filed1[j].getModifiers();
String priv = Modifier.toString(mo);
// 属性类型
Class<?> type = filed1[j].getType();
System.out.println(priv +
" "
+ type.getName() +
" "
+ filed1[j].getName() +
";"
);
}
6.获得某个类的全部方法:
Class<?> clazz = Class.forName(
"net.xsoftlab.baike.TestReflect"
);
Method method[] = clazz.getMethods();
for
(
int
i =
0
; i < method.length; ++i) {
// 返回值类型
Class<?> returnType = method[i].getReturnType();
// 参数
Class<?> para[] = method[i].getParameterTypes();
int
temp = method[i].getModifiers();
System.out.print(Modifier.toString(temp) +
" "
);
System.out.print(returnType.getName() +
" "
);
System.out.print(method[i].getName() +
" "
);
System.out.print(
"("
);
for
(
int
j =
0
; j < para.length; ++j) {
System.out.print(para[j].getName() +
" "
+
"arg"
+ j);
if
(j < para.length -
1
) {
System.out.print(
","
);
}
}
Class<?> exce[] = method[i].getExceptionTypes();
if
(exce.length >
0
) {
System.out.print(
") throws "
);
for
(
int
k =
0
; k < exce.length; ++k) {
System.out.print(exce[k].getName() +
" "
);
if
(k < exce.length -
1
) {
System.out.print(
","
);
}
}
}
else
{
System.out.print(
")"
);
}
System.out.println();
}