jva反射详解

来源:互联网 发布:维棠flv下载器 mac 编辑:程序博客网 时间:2024/06/06 01:14

源自:http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html

2011-09-02 14:16 by Rollen Holt, 258627 阅读, 98 评论, 收藏编辑

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

下面开始正文。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package Reflect;
 
/**
 * 通过一个对象获得完整的包名和类名
 * */
class Demo{
    //other codes...
}
 
class hello{
    public static void main(String[] args) {
        Demo demo=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{
    //other codes...
}
 
class hello{
    public static void main(String[] args) {
        Class<?> demo1=null;
        Class<?> demo2=null;
        Class<?> demo3=null;
        try{
            //一般尽量采用这种形式
            demo1=Class.forName("Reflect.Demo");
        }catch(Exception e){
            e.printStackTrace();
        }
        demo2=new Demo().getClass();
        demo3=Demo.class;
         
        System.out.println("类名称   "+demo1.getName());
        System.out.println("类名称   "+demo2.getName());
        System.out.println("类名称   "+demo3.getName());
         
    }
}

【运行结果】:

类名称   Reflect.Demo

类名称   Reflect.Demo

类名称   Reflect.Demo

【案例3】通过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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package Reflect;
 
class Person{
     
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(intage) {
        this.age = age;
    }
    @Override
    public String toString(){
        return "["+this.name+"  "+this.age+"]";
    }
    private String name;
    private int age;
}
 
class hello{
    public static void main(String[] args) {
        Class<?> demo=null;
        try{
            demo=Class.forName("Reflect.Person");
        }catch (Exception e) {
            e.printStackTrace();
        }
        Person per=null;
        try {
            per=(Person)demo.newInstance();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        per.setName("Rollen");
        per.setAge(20);
        System.out.println(per);
    }
}

【运行结果】:

[Rollen  20]

但是注意一下,当我们把Person中的默认的无参构造函数取消的时候,比如自己定义只定义一个有参数的构造函数之后,会出现错误:

比如我定义了一个构造函数:

?
1
2
3
4
public Person(String name, int age) {
        this.age=age;
        this.name=name;
    }

然后继续运行上面的程序,会出现:

java.lang.InstantiationException: Reflect.Person

    at java.lang.Class.newInstance0(Class.java:340)

    at java.lang.Class.newInstance(Class.java:308)

    at Reflect.hello.main(hello.java:39)

Exception in thread "main" java.lang.NullPointerException

    at Reflect.hello.main(hello.java:47)

所以大家以后再编写使用Class实例化其他类的对象的时候,一定要自己定义无参的构造函数

 

【案例】通过Class调用其他类中的构造函数(也可以通过这种方式通过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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package Reflect;
 
import java.lang.reflect.Constructor;
 
class Person{
     
    public Person() {
         
    }
    public Person(String name){
        this.name=name;
    }
    public Person(int age){
        this.age=age;
    }
    public Person(String name, intage) {
        this.age=age;
        this.name=name;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    @Override
    public String toString(){
        return "["+this.name+"  "+this.age+"]";
    }
    private String name;
    private int age;
}
 
class hello{
    public static void main(String[] args) {
        Class<?> demo=null;
        try{
            demo=Class.forName("Reflect.Person");
        }catch (Exception e) {
            e.printStackTrace();
        }
        Person per1=null;
        Person per2=null;
        Person per3=null;
        Person per4=null;
        //取得全部的构造函数
        Constructor<?> cons[]=demo.getConstructors();
        try{
            per1=(Person)cons[0].newInstance();
            per2=(Person)cons[1].newInstance("Rollen");
            per3=(Person)cons[2].newInstance(20);
            per4=(Person)cons[3].newInstance("Rollen",20);
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println(per1);
        System.out.println(per2);
        System.out.println(per3);
        System.out.println(per4);
    }
}

【运行结果】:

[null  0]

[Rollen  0]

[null  20]

[Rollen  20]

【案例】 

返回一个类实现的接口:

?
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
36
37
38
39
40
41
42
43
44
45
46
47
48
package Reflect;
 
interface China{
    public static final String name="Rollen";
    public static  int age=20;
    public void sayChina();
    public void sayHello(String name,int age);
}
 
class Person implements China{
    public Person() {
         
    }
    public Person(String sex){
        this.sex=sex;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public void sayChina(){
        System.out.println("hello ,china");
    }
    @Override
    public void sayHello(String name,int age){
        System.out.println(name+"  "+age);
    }
    private String sex;
}
 
class hello{
    public static void main(String[] args) {
        Class<?> demo=null;
        try{
            demo=Class.forName("Reflect.Person");
        }catch (Exception e) {
            e.printStackTrace();
        }
        //保存所有的接口
        Class<?> intes[]=demo.getInterfaces();
        for (int i =0; i < intes.length; i++) {
            System.out.println("实现的接口   "+intes[i].getName());
        }
    }
}

【运行结果】:

实现的接口   Reflect.China

(注意,以下几个例子,都会用到这个例子的Person类,所以为节省篇幅,此处不再粘贴Person的代码部分,只粘贴主类hello的代码)

【案例】:取得其他类中的父类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class hello{
    public static void main(String[] args) {
        Class<?> demo=null;
        try{
            demo=Class.forName("Reflect.Person");
        }catch (Exception e) {
            e.printStackTrace();
        }
        //取得父类
        Class<?> temp=demo.getSuperclass();
        System.out.println("继承的父类为:   "+temp.getName());
    }
}

【运行结果】

继承的父类为:   java.lang.Object

【案例】:获得其他类中的全部构造函数

这个例子需要在程序开头添加import java.lang.reflect.*;

然后将主类编写为:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class hello{
    public static void main(String[] args) {
        Class<?> demo=null;
        try{
            demo=Class.forName("Reflect.Person");
        }catch (Exception e) {
            e.printStackTrace();
        }
        Constructor<?>cons[]=demo.getConstructors();
        for (int i =0; i < cons.length; i++) {
            System.out.println("构造方法:  "+cons[i]);
        }
    }
}

【运行结果】:

构造方法:  public Reflect.Person()

构造方法:  public Reflect.Person(java.lang.String)

但是细心的读者会发现,上面的构造函数没有public 或者private这一类的修饰符

下面这个例子我们就来获取修饰符

?
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
class hello{
    public static void main(String[] args) {
        Class<?> demo=null;
        try{
            demo=Class.forName("Reflect.Person");
        }catch (Exception e) {
            e.printStackTrace();
        }
        Constructor<?>cons[]=demo.getConstructors();
        for (int i =0; i < cons.length; i++) {
            Class<?> p[]=cons[i].getParameterTypes();
            System.out.print("构造方法:  ");
            int mo=cons[i].getModifiers();
            System.out.print(Modifier.toString(mo)+" ");
            System.out.print(cons[i].getName());
            System.out.print("(");
            for(int j=0;j<p.length;++j){
                System.out.print(p[j].getName()+" arg"+i);
                if(j<p.length-1){
                    System.out.print(",");
                }
            }
            System.out.println("){}");
        }
    }
}

【运行结果】:

构造方法:  public Reflect.Person(){}

构造方法:  public Reflect.Person(java.lang.String arg1){}

有时候一个方法可能还有异常,呵呵。下面看看:

?
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
36
37
38
39
class hello{
    public static void main(String[] args) {
        Class<?> demo=null;
        try{
            demo=Class.forName("Reflect.Person");
        }catch (Exception e) {
            e.printStackTrace();
        }
        Method method[]=demo.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();
        }
    }
}

【运行结果】:

public java.lang.String  getSex ()

public void  setSex (java.lang.String arg0)

public void  sayChina ()

public void  sayHello (java.lang.String arg0,int arg1)

public final native void  wait (long arg0) throws java.lang.InterruptedException

public final void  wait () throws java.lang.InterruptedException

public final void  wait (long arg0,int arg1) throws java.lang.InterruptedException

public boolean  equals (java.lang.Object arg0)

public java.lang.String  toString ()

public native int  hashCode ()

public final native java.lang.Class  getClass ()

public final native void  notify ()

public final native void  notifyAll ()

【案例】接下来让我们取得其他类的全部属性吧,最后我讲这些整理在一起,也就是通过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
26
27
28
29
30
31
32
33
34
class hello {
    public static void main(String[] args) {
        Class<?> demo = null;
        try {
            demo = Class.forName("Reflect.Person");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("===============本类属性========================");
        // 取得本类的全部属性
        Field[] field = demo.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 = demo.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() + ";");
        }
    }
}

【运行结果】:

===============本类属性========================

private java.lang.String sex;

===============实现的接口或者父类的属性========================

public static final java.lang.String name;

public static final int age;

【案例】其实还可以通过反射调用其他类中的方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class hello {
    public static void main(String[] args) {
        Class<?> demo = null;
        try {
            demo = Class.forName("Reflect.Person");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try{
            //调用Person类中的sayChina方法
            Method method=demo.getMethod("sayChina");
            method.invoke(demo.newInstance());
            //调用Person的sayHello方法
            method=demo.getMethod("sayHello", String.class,int.class);
            method.invoke(demo.newInstance(),"Rollen",20);
             
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  【运行结果】:

hello ,china

Rollen  20

【案例】调用其他类的set和get方法

?
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class hello {
    public static void main(String[] args) {
        Class<?> demo = null;
        Object obj=null;
        try {
            demo = Class.forName("Reflect.Person");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try{
         obj=demo.newInstance();
        }catch (Exception e) {
            e.printStackTrace();
        }
        setter(obj,"Sex","男",String.class);
        getter(obj,"Sex");
    }
 
    /**
     * @param obj
     *            操作的对象
     * @param att
     *            操作的属性
     * */
    public static void getter(Object obj, String att) {
        try {
            Method method = obj.getClass().getMethod("get"+ att);
            System.out.println(method.invoke(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * @param obj
     *            操作的对象
     * @param att
     *            操作的属性
     * @param value
     *            设置的值
     * @param type
     *            参数的属性
     * */
    public static void setter(Object obj, String att, Object value,
            Class<?> type) {
        try {
            Method method = obj.getClass().getMethod("set"+ att, type);
            method.invoke(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}// end class

【运行结果】:

 【案例】通过反射操作属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class hello {
    public static void main(String[] args) throws Exception {
        Class<?> demo = null;
        Object obj = null;
 
        demo = Class.forName("Reflect.Person");
        obj = demo.newInstance();
 
        Field field = demo.getDeclaredField("sex");
        field.setAccessible(true);
        field.set(obj, "男");
        System.out.println(field.get(obj));
    }
}// end class

【案例】通过反射取得并修改数组的信息:

?
1
2
3
4
5
6
7
8
9
10
11
12
import java.lang.reflect.*;
class hello{
    public static void main(String[] args) {
        int[] temp={1,2,3,4,5};
        Class<?>demo=temp.getClass().getComponentType();
        System.out.println("数组类型: "+demo.getName());
        System.out.println("数组长度  "+Array.getLength(temp));
        System.out.println("数组的第一个元素: "+Array.get(temp,0));
        Array.set(temp, 0, 100);
        System.out.println("修改之后数组第一个元素为: "+Array.get(temp,0));
    }
}

【运行结果】:

数组类型: int

数组长度  5

数组的第一个元素: 1

修改之后数组第一个元素为: 100

【案例】通过反射修改数组大小

?
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
class hello{
    public static void main(String[] args) {
        int[] temp={1,2,3,4,5,6,7,8,9};
        int[] newTemp=(int[])arrayInc(temp,15);
        print(newTemp);
        System.out.println("=====================");
        String[] atr={"a","b","c"};
        String[] str1=(String[])arrayInc(atr,8);
        print(str1);
    }
     
    /**
     * 修改数组大小
     * */
    public static Object arrayInc(Object obj,intlen){
        Class<?>arr=obj.getClass().getComponentType();
        Object newArr=Array.newInstance(arr, len);
        int co=Array.getLength(obj);
        System.arraycopy(obj, 0, newArr,0, co);
        return newArr;
    }
    /**
     * 打印
     * */
    public static void print(Object obj){
        Class<?>c=obj.getClass();
        if(!c.isArray()){
            return;
        }
        System.out.println("数组长度为: "+Array.getLength(obj));
        for (int i =0; i < Array.getLength(obj); i++) {
            System.out.print(Array.get(obj, i)+" ");
        }
    }
}

【运行结果】:

数组长度为: 15

1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 =====================

数组长度为: 8

a b c null null null null null

动态代理

【案例】首先来看看如何获得类加载器:

?
1
2
3
4
5
6
7
8
9
class test{
     
}
class hello{
    public static void main(String[] args) {
        test t=new test();
        System.out.println("类加载器  "+t.getClass().getClassLoader().getClass().getName());
    }
}

【程序输出】:

类加载器  sun.misc.Launcher$AppClassLoader

其实在java中有三种类类加载器。

1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。

2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jre\lib\ext目录中的类

3)AppClassLoader 加载classpath指定的类,是最常用的加载器。同时也是java中默认的加载器。

如果想要完成动态代理,首先需要定义一个InvocationHandler接口的子类,已完成代理的具体操作。

?
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
36
37
38
39
40
41
package Reflect;
import java.lang.reflect.*;
 
//定义项目接口
interface Subject {
    public String say(String name, intage);
}
 
// 定义真实项目
class RealSubject implements Subject {
    @Override
    public String say(String name, intage) {
        return name + "  "+ age;
    }
}
 
class MyInvocationHandler implements InvocationHandler {
    private Object obj = null;
 
    public Object bind(Object obj) {
        this.obj = obj;
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
                .getClass().getInterfaces(), this);
    }
 
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Object temp = method.invoke(this.obj, args);
        return temp;
    }
}
 
class hello {
    public static void main(String[] args) {
        MyInvocationHandler demo = newMyInvocationHandler();
        Subject sub = (Subject) demo.bind(newRealSubject());
        String info = sub.say("Rollen",20);
        System.out.println(info);
    }
}

【运行结果】:

Rollen  20

类的生命周期

在一个类编译完成之后,下一步就需要开始使用类,如果要使用一个类,肯定离不开JVM。在程序执行中JVM通过装载,链接,初始化这3个步骤完成。

类的装载是通过类加载器完成的,加载器将.class文件的二进制文件装入JVM的方法区,并且在堆区创建描述这个类的java.lang.Class对象。用来封装数据。但是同一个类只会被类装载器装载以前

链接就是把二进制数据组装为可以运行的状态。

 

链接分为校验,准备,解析这3个阶段

校验一般用来确认此二进制文件是否适合当前的JVM(版本),

准备就是为静态成员分配内存空间,。并设置默认值

解析指的是转换常量池中的代码作为直接引用的过程,直到所有的符号引用都可以被运行程序使用(建立完整的对应关系)

完成之后,类型也就完成了初始化,初始化之后类的对象就可以正常使用了,直到一个对象不再使用之后,将被垃圾回收。释放空间。

当没有任何引用指向Class对象时就会被卸载,结束类的生命周期

将反射用于工厂模式

先来看看,如果不用反射的时候,的工厂模式吧:

http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144851.html

?
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
36
37
38
39
40
41
/**
 * @author Rollen-Holt 设计模式之 工厂模式
 */
 
interface fruit{
    public abstract voideat();
}
 
class Apple implements fruit{
    public void eat(){
        System.out.println("Apple");
    }
}
 
class Orange implements fruit{
    public void eat(){
        System.out.println("Orange");
    }
}
 
// 构造工厂类
// 也就是说以后如果我们在添加其他的实例的时候只需要修改工厂类就行了
class Factory{
    public static fruit getInstance(String fruitName){
        fruit f=null;
        if("Apple".equals(fruitName)){
            f=new Apple();
        }
        if("Orange".equals(fruitName)){
            f=new Orange();
        }
        return f;
    }
}
class hello{
    public static void main(String[] a){
        fruit f=Factory.getInstance("Orange");
        f.eat();
    }
 
}

这样,当我们在添加一个子类的时候,就需要修改工厂类了。如果我们添加太多的子类的时候,改的就会很多。

现在我们看看利用反射机制:

?
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
36
37
package Reflect;
 
interface fruit{
    public abstract voideat();
}
 
class Apple implements fruit{
    public void eat(){
        System.out.println("Apple");
    }
}
 
class Orange implements fruit{
    public void eat(){
        System.out.println("Orange");
    }
}
 
class Factory{
    public static fruit getInstance(String ClassName){
        fruit f=null;
        try{
            f=(fruit)Class.forName(ClassName).newInstance();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }
}
class hello{
    public static void main(String[] a){
        fruit f=Factory.getInstance("Reflect.Apple");
        if(f!=null){
            f.eat();
        }
    }
}

现在就算我们添加任意多个子类的时候,工厂类就不需要修改。

 

上面的爱吗虽然可以通过反射取得接口的实例,但是需要传入完整的包和类名。而且用户也无法知道一个接口有多少个可以使用的子类,所以我们通过属性文件的形式配置所需要的子类。

下面我们来看看: 结合属性文件的工厂模式

首先创建一个fruit.properties的资源文件,

内容为:

?
1
2
apple=Reflect.Apple
orange=Reflect.Orange

 然后编写主类代码:

?
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package Reflect;
 
import java.io.*;
import java.util.*;
 
interface fruit{
    public abstract voideat();
}
 
class Apple implements fruit{
    public void eat(){
        System.out.println("Apple");
    }
}
 
class Orange implements fruit{
    public void eat(){
        System.out.println("Orange");
    }
}
 
//操作属性文件类
class init{
    public static Properties getPro()throws FileNotFoundException, IOException{
        Properties pro=new Properties();
        File f=new File("fruit.properties");
        if(f.exists()){
            pro.load(new FileInputStream(f));
        }else{
            pro.setProperty("apple","Reflect.Apple");
            pro.setProperty("orange","Reflect.Orange");
            pro.store(new FileOutputStream(f),"FRUIT CLASS");
        }
        return pro;
    }
}
 
class Factory{
    public static fruit getInstance(String ClassName){
        fruit f=null;
        try{
            f=(fruit)Class.forName(ClassName).newInstance();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }
}
class hello{
    public static void main(String[] a) throws FileNotFoundException, IOException{
        Properties pro=init.getPro();
        fruit f=Factory.getInstance(pro.getProperty("apple"));
        if(f!=null){
            f.eat();
        }
    }
}

【运行结果】:Apple
















==============================================================================
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员

==============================================================================
绿色通道: 好文要顶 关注我 收藏该文与我联系
Rollen Holt
关注 - 40
粉丝 - 1681
+加关注
105    
0
    (请您对文章做出评价)    
«上一篇:java中类的生命周期
»下一篇:java对象克隆和序列化
  • 分类: Java

  

< Prev12
Add your comment
  1. #51楼瘟疫之源   2013-08-23 13:13
    感觉撸主有的地方是错误的,撸主的程序自己调试过了吗?
    支持(0)反对(0)
  2. #52楼一般不扯淡   2013-08-30 09:04
    通过getConstructor() 获得Constructor[] 的方式用的太少了,楼主的案例有点错误
    支持(2)反对(0)
  3. #53楼Harry Potter   2013-09-12 12:18
    @Edward_TC
    我也碰到了,用1.6没问题,1.7也报这个错,应该是SDK版本的原因
    支持(0)反对(0)
  4. #54楼It's   2013-09-18 10:53
    但是细心的读者会发现,上面的构造函数没有public 或者private这一类的修饰符
      这么怎么说???
    支持(0)反对(1)
    http://pic.cnitblog.com/face/485668/20130501153851.png
  5. #55楼cherish2015   2013-09-22 12:38
    good,very good,haha
    支持(0)反对(0)
  6. #56楼牛_   2013-09-28 21:22
    getFields()獲取本類中的pulic屬性以及父類或者接口中繼承過來的屬性
    支持(0)反对(0)
    http://pic.cnitblog.com/face/306300/20140409000705.png
  7. #57楼Chunwai Yeung   2013-10-10 13:48
    的确称得上是详解了,做完实验,受用了,(*^__^*)
    支持(0)反对(0)
  8. #58楼鸢尾花骑士   2013-10-22 10:23
    非常NICE

    不过一直不明白,  反射有什么用呢
    支持(0)反对(0)
  9. #59楼[楼主]Rollen Holt   2013-10-22 10:40
    @鸢尾花骑士
    引用非常NICE

    不过一直不明白,  反射有什么用呢

    反射一般用来写一些通用的框架。比如ide的自动提示就是根据反射来整的
    支持(0)反对(0)
    http://pic.cnitblog.com/face/243280/20140807185513.png
  10. #60楼GYI_Feison   2013-11-05 20:12
    好文,赞个
    支持(0)反对(0)
  11. #61楼WangWeidang   2013-11-23 15:19
    但是细心的读者会发现,上面的构造函数没有public 或者private这一类的修饰符



    这里没有读懂呀
    支持(1)反对(0)
  12. #62楼陈霸先   2013-11-29 11:44
    @gu_sofia
    sdk1.7,
    我的
    public Person(String name, int age) {
            this.age=age;
            this.name=name;
            }
    public Person(String name){
    this.name = name;
    }
    public Person(int age){
    this.age  = age;
    }
    public Person() {

            }

    输出顺序是
    System.out.println("GG"+cons[0]);
    System.out.println("GG"+cons[1]);
    System.out.println("GG"+cons[2]);
    System.out.println("GG"+cons[3]);
    GGpublic com.cjl.www.Person(java.lang.String)
    GGpublic com.cjl.www.Person(java.lang.String,int)
    GGpublic com.cjl.www.Person(int)
    GGpublic com.cjl.www.Person()

    希望对大家有所帮助,自己打印cons看下内部顺序
    支持(0)反对(0)
  13. #63楼fkblog.org   2014-01-13 13:56
    最近正整java,发现太强大了,好好学,也推荐个教程:http://www.w3cschool.cc/java/java-tutorial.html
    支持(0)反对(1)
  14. #64楼乒乓球鸡蛋   2014-01-15 10:45
    很不错,学了很多;

    1、工厂模式就是根据名字返回对象;
    2、反射就是通过名字返回类的所有相关类、属性、加载器、父类、接口等信息
    支持(0)反对(0)
    http://pic.cnitblog.com/face/u275232.jpg?id=29160949
  15. #65楼沧海一滴   2014-04-13 13:55
    @鸢尾花骑士
    解耦
    支持(0)反对(0)
    http://pic.cnitblog.com/face/280044/20130730175146.png
  16. #66楼沧海一滴   2014-04-13 22:49
    package reflect.test;

    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;

    import reflect.model.Staff;

    import common.GenenrateData;

    public class InitializeClassWithSeveralConstructorWithReflect {

    public static void main(String[] args){

    String classNameWithFullQualified="reflect.model.Staff";

    Class<?> commonClass=null;
    Constructor<?>[] constructors=null;

    try {
    commonClass=Class.forName(classNameWithFullQualified);
    constructors=commonClass.getConstructors();
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    Staff s1=null;
    Staff s2=null;
    Staff s3=null;
    Staff s4=null;

    try {

    int paramNum=0;
    for (Constructor<?> constructor : constructors) {
    paramNum=constructor.getParameterTypes().length;
    if (paramNum==0) {
    s1=(Staff) constructor.newInstance();

    }else if(paramNum==1){
    s2=(Staff) constructor.newInstance(String.valueOf(GenenrateData.genenerateInt()));

    }else if (paramNum==2) {
    s3=(Staff) constructor.newInstance(String.valueOf(GenenrateData.genenerateInt()),"tes1");

    }else if (paramNum==3) {
    s4=(Staff) constructor.newInstance(String.valueOf(GenenrateData.genenerateInt()),"tes1","tec1");

    }
    }


    } catch (InstantiationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }


    System.out.println(s1.toString());
    System.out.println(s2.toString());
    System.out.println(s3.toString());
    System.out.println(s4.toString());

    }

    }
    支持(0)反对(0)
    http://pic.cnitblog.com/face/280044/20130730175146.png
  17. #67楼沧海一滴   2014-04-13 22:49
    package reflect.model;

    public class Staff {

    public String getStaffId() {
    return staffId;
    }
    public void setStaffId(String staffId) {
    this.staffId = staffId;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public String getDepart() {
    return depart;
    }
    public void setDepart(String depart) {
    this.depart = depart;
    }


    public Staff() {
    // TODO Auto-generated constructor stub
    }

    public Staff(String staffId) {
    // TODO Auto-generated constructor stub
    this.staffId=staffId;
    }

    public Staff(String staffId,String name) {
    // TODO Auto-generated constructor stub
    this.staffId=staffId;
    this.name=name;
    }


    public Staff(String staffId,String name,String depart) {
    // TODO Auto-generated constructor stub
    this.staffId=staffId;
    this.name=name;
    this.depart=depart;
    }

    @Override
    public String toString() {
    // TODO Auto-generated method stub
    return new StringBuffer(50).append("[")
    .append(this.staffId)
    .append(",")
    .append(this.name)
    .append(",")
    .append(this.depart)
    .append("]")
    .toString();
    }

    private String staffId;
    private String name;
    private String depart;

    }
    支持(0)反对(0)
    http://pic.cnitblog.com/face/280044/20130730175146.png
  18. #68楼沧海一滴   2014-04-13 22:49
    不同构造函数的那个部分,硬编码了。
    支持(0)反对(0)
    http://pic.cnitblog.com/face/280044/20130730175146.png
  19. #69楼beyondchina   2014-04-17 15:54
    mark. 写得很不错,就是有些地方写错了还没改过来。
    支持(0)反对(0)
    http://pic.cnitblog.com/face/507671/20130326144957.png
  20. #70楼yzhilzcy4   2014-06-17 11:19
    @huangzhtao
    me too
    支持(0)反对(0)
    http://pic.cnitblog.com/face/u444791.jpg?id=05172533
  21. #71楼alston_king   2014-07-02 17:23
    总结的不错,学习了。
    给32个赞
    支持(0)反对(0)
  22. #72楼牙鱼   2014-07-06 14:50
    很不错,就是缺少一些说明,
    支持(0)反对(0)
  23. #73楼阿超-   2014-07-11 20:32
    可以哦……
    支持(0)反对(0)
  24. #74楼美人如此多娇   2014-07-16 14:17
    撸主的案例简述中,“获取其他类中的XXX”,听的好别扭!!!!!
    支持(0)反对(0)
    http://pic.cnitblog.com/face/u472397.png?id=12220144
  25. #75楼leesf   2014-08-19 14:48
    @瘟疫之源
    有些地方需要自己调试的,不同机器上得到的结果不相同(比如getConstructors()得到的构造器的顺序和楼主的可能不相同)。
    支持(0)反对(0)
  26. #76楼小安妮的熊   2014-08-27 08:54
    博主太给力了,大爱你!
    支持(0)反对(0)
  27. #77楼SnowOnion   2014-08-27 10:21
    > 添加一句:所有类的对象其实都是Class的实例。

    不太对.
    所有对象都是 Object 的实例倒是真的...
    或者, 所有对象的 getClass() 返回 Class 实例也是对的...
    支持(1)反对(0)
  28. #78楼明凯   2014-09-15 11:32
    很好啊,大神
    支持(0)反对(0)
    http://pic.cnitblog.com/face/672384/20140915110651.png
  29. #79楼longsan   2014-09-24 21:48
    楼主,写的真好,学习了。
    支持(0)反对(0)
    http://pic.cnitblog.com/face/440229/20131203102100.png
  30. #80楼shl1988012   2014-09-28 19:26
    我学习的榜样.....谢谢楼主
    支持(0)反对(0)
  31. #81楼千泷先生   2014-10-13 09:13
    牛逼,好文,没仔细的去一个一个的看
    支持(0)反对(0)
  32. #82楼googny   2014-10-15 21:36
    哈哈 干货  看一次,赞一次。
    支持(0)反对(0)
    http://pic.cnitblog.com/face/409148/20140422191536.png
  33. #83楼刘勇奇   2014-10-21 16:22
    好,果断收藏了
    支持(0)反对(0)
    http://pic.cnitblog.com/face/522648/20130428112853.png
  34. #84楼CTJ   2014-10-29 20:05
    这篇文章跟我看的那个JAVA开发实战经典基本一样啊~不过还是赞一个,写得还是不错的。
    支持(0)反对(0)
  35. #85楼liuqidong_hn   2014-11-14 13:29
    good,通俗易懂
    支持(0)反对(0)
  36. #86楼D丶阿南   2014-11-24 17:09
    赞一个
    支持(0)反对(0)
  37. #87楼hety   2014-12-01 15:07
    不知道有没有错,反正很nb的样子
    支持(0)反对(0)
  38. #88楼TomGao   2014-12-05 10:37
    “所有类的对象其实都是Class的实例。”
    这句话我认为严重错误。
    当一个类被加载,或当加载器(class loader)的defineClass()被JVM调用,JVM 便自动产生一个Class 对象。也就是说:每个类的Class实例只有一个。每个类的Class实例跟类的对象根本不是一回事!
    支持(0)反对(0)
  39. #89楼freshman__   2014-12-14 19:57
    Class的实例应该就是字节码,一个类的字节码就一份,所以一个类就一个Class实例
    支持(1)反对(0)
  40. #90楼fomeiherz   2014-12-27 09:37
    写的很详细,赞一个
    支持(0)反对(0)
  41. #91楼北言   2015-01-29 20:50
    写的很好,学习了
    支持(0)反对(0)
  42. #92楼SAP师太   2015-01-30 00:02
    反射是很用来的,特别是写些动态的程序、框架之类的,以前玩过,不错!
    支持(0)反对(0)
    http://pic.cnitblog.com/face/717614/20150128073001.png
  43. #93楼Miracle_lucy   2015-02-10 23:15
    @freshman__
    支持一个
    支持(0)反对(0)
    http://pic.cnitblog.com/face/490089/20131218135249.png
  44. #94楼Miracle_lucy   2015-02-10 23:24
    @青春丶冭柔情
    楼主是女生?看文风像是男生呀
    支持(0)反对(0)
    http://pic.cnitblog.com/face/490089/20131218135249.png
  45. #95楼蓝田364251   2015-02-12 11:26
    虽然没有资格评论,但是还是觉得写的很好。
    支持(0)反对(0)
  46. #96楼活下去   2015-03-17 16:42
    写的很受用!一些地方有点bug。。。看的运行结果觉得有点问题,逼着我自己动手去调试了啊////
    支持(0)反对(0)
  47. #97楼方方和圆圆   2015-03-17 18:38
    @瘟疫之源
    大概知道哪里错了,都是小问题
    支持(0)反对(0)
    http://pic.cnitblog.com/face/497865/20150117172039.png
  48. #98楼31430182015/3/17 18:39:00 方方和圆圆   2015-03-17 18:39
    真不错, 学习了,谢谢楼主,O(∩_∩)o

 

0 0
原创粉丝点击