Java反射机制例子(一)

来源:互联网 发布:剑灵卡刀软件2017 编辑:程序博客网 时间:2024/05/20 06:53

本篇文章依旧采用小例子来说明,因为我始终觉的,案例驱动是最好的,要不然只看理论的话,看了也不懂,不过建议大家在看完文章之后,在回过头去看看理论,会有更好的理解。

下面开始正文。

【案例1】通过一个对象获得完整的包名和类名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package Reflect;
 
class Demo{
    //othercodes...
}
 
class hello{
    public static void main(String[]args) {
        Demodemo=new Demo();
        System.out.println(demo.getClass().getName());
    }
}

【运行结果】:Reflect.Demo

添加一句:所有类的对象其实都是Class的实例。

【案例2】实例化Class类对象

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
package Reflect;
class Demo{
    //othercodes...
}
 
class hello{
    public static void main(String[]args) {
        Class
0 0