經過java類反射獲取類模板

    在java語言中萬事萬物皆爲對象,例如咱們寫一個person類那麼咱們就能夠經過這個類來創造一些實例,這裏的「實例」就是咱們平時使用的對象。java

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"就是咱們能吃的月餅了。this

    但人是一種喜歡思考的動物(因此智人才在尼安德特人 、魯道夫人 、直立人等中被「天然選擇」了出來,站到食物鏈頂端),那麼咱們不由要想Person這個類模板是由誰創造的呢? 也就是說製做月餅模具的機牀又在哪呢?
spa

    那麼下來就該咱們的Class類粉墨登場了,它位於java.lang這個包下因爲這個源碼過長故在此貼出它的部分源碼:code

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,就代表不但願從這個類被繼承,不但願被修改)下面咱們將具體操做這個類看看它是怎麼來生產咱們的類模具的。orm

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類的類模具,下面咱們來具體演示:get

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")」至關於咱們把一個生產模具的圖紙來交給機牀,機牀根據這個圖紙來生產對應的模具。源碼

相關文章
相關標籤/搜索