通过java类反射获取类模板

    在java语言中万事万物皆为对象,例如我们写一个person类那么我们就可以通过这个类来创造一些实例,这里的“实例”就是我们平时使用的对象。

public class Person {
	private String name;
	private int age;
	private String sex;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
	
}
ppublic class Referce {
	public static void main(String[] args) {
		Person wangwu=new Person();
		Person zhaosi=new Person();
		wangwu.setName("王五");
		wangwu.setAge(18);
		wangwu.setSex("male");
		
		zhaosi.setName("赵四");
		zhaosi.setAge(22);
		zhaosi.setSex("female");
	}
}

    在上面的代码中的“wangwu”、“zhaosi”就是我们所创造出来的对象,也就是说“Person”相当于一个模板,我们可以通过这个模板来创造“wangwu”、“zhaosi”这些具体的对象。举个通俗的栗子“Person”就相当于我们用来制作月饼的模具,“wangwu”、"zhaosi"就是我们能吃的月饼了。

    但人是一种喜欢思考的动物(所以智人才在尼安德特人 、鲁道夫人 、直立人等中被“自然选择”了出来,站到食物链顶端),那么我们不禁要想Person这个类模板是由谁创造的呢? 也就是说制作月饼模具的机床又在哪呢?

    那么下来就该我们的Class类粉墨登场了,它位于java.lang这个包下由于这个源码过长故在此贴出它的部分源码:

public final class Class<T> implements java.io.Serializable,
                              GenericDeclaration,
                              Type,
                              AnnotatedElement {
    private static final int ANNOTATION= 0x00002000;
    private static final int ENUM      = 0x00004000;
    private static final int SYNTHETIC = 0x00001000;

    private static native void registerNatives();
    static {
        registerNatives();
    }

    /*
     * Private constructor. Only the Java Virtual Machine creates Class objects.
     * This constructor is not used and prevents the default constructor being
     * generated.
     */
    private Class(ClassLoader loader) {
        // Initialize final field for classLoader.  The initialization value of non-null
        // prevents future JIT optimizations from assuming this final field is null.
        classLoader = loader;
    }

    /**
     * Converts the object to a string. The string representation is the
     * string "class" or "interface", followed by a space, and then by the
     * fully qualified name of the class in the format returned by
     * {@code getName}.  If this {@code Class} object represents a
     * primitive type, this method returns the name of the primitive type.  If
     * this {@code Class} object represents void this method returns
     * "void".
     *
     * @return a string representation of this class object.
     */
    public String toString() {
        return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
            + getName();
    }

    我们可以看出它是一个final类(整个类都是final,就表明不希望从这个类被继承,不希望被修改)下面我们将具体操作这个类看看它是怎么来生产我们的类模具的。

public class Test {
	public static void main(String[] args) {
		Class<Person> clazz=Person.class;
		System.out.println(clazz.getName());
	}
}
输出结果是:com.tl.referce.Person

    从输出结果上我们可以看出这个clazz对象就是Person的类模具了,那么既然现在获取到了Person的类模具了那么是不是就可以利用它(clazz)来生产Person对象了呢?

public class Test {
	public static void main(String[] args) {
		Class<Person> clazz=Person.class;
		try {
			Person wangwu=clazz.newInstance();
			wangwu.setName("王五");
			wangwu.setAge(18);
			wangwu.setSex("male");
			System.out.println("姓名:"+wangwu.getName()+",年龄:"+wangwu.getAge()+",性别:"+wangwu.getSex());
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}
输出结果是:姓名:王五,年龄:18,性别:male

    从输出结果我们可以看出,我们已经正确的拿到了Person类的类模具而且成功的利用这个模具创造出了“wangwu”这个对象。

    实际中我们还可以通过其他两种方法来获取Person类的类模具,下面我们来具体演示:

public class Test {
	public static void main(String[] args) {
		Person wangwu=new Person();
		Class<Person> clazz1=(Class<Person>) wangwu.getClass();
		System.out.println(clazz1.getName());
		System.out.println("=========================================");
		try {
			Class<Person> clazz2=(Class<Person>) Class.forName("com.tl.referce.Person");
			System.out.println(clazz2.getName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}
}

输出结果:
com.tl.referce.Person
=========================================
com.tl.referce.Person

    从输出结果可以看出这三种方法都可以获取Person类的类模具,“wangwu.getClass()”这种方法是我们通过一个具体的对象来获取类模具,相当于通过一个五仁月饼来反向制造出五仁月饼的具。“Class.forName("com.tl.referce.Person")”相当于我们把一个生产模具的图纸来交给机床,机床根据这个图纸来生产对应的模具。

转载于:https://my.oschina.net/u/2260218/blog/513492

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值