3
4
5
6
7
8
|
package net.xsoftlab.baike; public class TestReflect { public static void main(String[] args) throws Exception { TestReflect testReflect = new TestReflect(); System.out.println(testReflect.getClass().getName()); // 结果 net.xsoftlab.baike.TestReflect } } |
package
net.xsoftlab.baike;
public
class
TestReflect {
public
static
void
main(String[] args)
throws
Exception {
Class<?> class1 =
null
;
Class<?> class2 =
null
;
Class<?> class3 =
null
;
// 一般采用这种形式
class1 = Class.forName(
"net.xsoftlab.baike.TestReflect"
);
class2 =
new
TestReflect().getClass();
class3 = TestReflect.
class
;
System.out.println(
"类名称 "
+ class1.getName());
System.out.println(
"类名称 "
+ class2.getName());
System.out.println(
"类名称 "
+ class3.getName());
}
}
package
net.xsoftlab.baike;
import
java.io.Serializable;
public
class
TestReflect
implements
Serializable {
private
static
final
long
serialVersionUID = -2862585049955236662L;
public
static
void
main(String[] args)
throws
Exception {
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());
}
// clazz实现的接口有:
// 1:java.io.Serializable
}
}