先來講說一些基本的概念: html
class:一個類有多個對象(實例)。在內存中類只有一份,而實例有多份。(這對於Java鎖的運行是十分重要的) java
Type 與Class的關係: this
概念: spa
類型的概念與值的概念相對立,前者是程序中的概念,後者則是程序運行時的概念,二者經過標識值的語言成分(例如,變量、表達式等)聯繫起來。 .net
好比變量v說明爲具備類型T,類型T所刻劃的值集爲{v1,v2,…vn,…},則變量v運行時能取且只能取某個vi爲值。因而可知,類型規定了具備該類型的變量或表達式的取值範圍。 code
共性:
在對象式語言中,「值」爲對象(或對象指引,但本質上仍爲對象)。因此,對象式語言中的類型刻劃了一組對象及其上可施行的操做。類型所刻劃的對象稱爲類型的實例。類也刻劃了一組對象。 orm
二者的共性在於兩者均刻劃了一組對象及其上的操做(在前面關於類的討論中,並未強調類刻劃對象上的操做這一事實),因此,既能夠說對象是類型的實例,也能夠說對象是類的實例,類型和類在與對象的關係上是相同的。不過,類型欲刻劃一組對象及其上的操做,必須藉助於類,由於類是達到這種目的的惟一設施。因而可知,類型是以類爲基礎的,是經過類來定義的,這體現了兩者的聯繫。 htm
區別:
l 做用不一樣 對象
類是程序的構造單位,是描述一組對象及其上操做的惟一語言成分,故其做用主要是具體描述這組對象,提供運行時建立這些對象的「模板」。例如,基於類間的繼承關係的派生類定義設施就反映了類在描述對象方面的做用。 blog
類型則是標誌變量或表達式取值範圍的一種語言成分,其做用主要是對這些變量或表達式運行時的取值進行約束。例如,對賦值語句左部的變量和右部的表達式的類型匹配檢查就反映了類型的約束做用。
l 與對象聯繫的緊密程序不一樣
類描述對象的具體形式和其上可施行的具體操做,且強調所描述的一組對象的共性,於是,與具體對象聯繫較密切,而與對象集的大小則聯繫較少。
類型強調所描述的一組對象的範圍和可施行操做的範圍,與對象集的大小聯繫較密切,而與其中具體對象則聯繫較少。
/*類描述了實例能作什麼,而類型決定了實例能作多大的事
*/
//這句話感受是對的,但我還找不到很好的說明,往後再來解決。
l 並非全部類均可直接做爲類型使用
類是類型的基礎,類型靠類來定義,有些類可直接做爲類型來使用,在這種意義下,咱們也可稱這些類是類型。
可是,也有一些類不能直接做爲類型來使用,這是由於,從類型的約束做用來看,類型強調所刻劃的對象的肯定性,即對象範圍的肯定性。所以,只有所描述的對象的範圍肯定的類纔可直接用做類型。
//下面就是反射的實例反射經常使用 Constructor,Field,Method.
package com.it.train.reject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Created by 55 on 2016/4/6. */ public class ReflectTest { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public ReflectTest() { } public ReflectTest(int age) { this.age = age; } public ReflectTest copy(ReflectTest object) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class invokeTestInstance = object.getClass(); Field[] fields = invokeTestInstance.getDeclaredFields(); for(Field field:fields){ String fieldName = field.getName(); String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1); String setMethodName = "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1); System.out.println(field.getType()); Method getMethod = invokeTestInstance.getMethod(getMethodName, new Class[]{}); Method setMethod = invokeTestInstance.getMethod(setMethodName, field.getType()); Object value = getMethod.invoke(object, new Object[]{}); setMethod.invoke(object, value); } //invokeTestInstance.getConstructor(); return object; } public void add(){ System.out.println("add"); } public void add(Integer a){ System.out.println(a.intValue() + age); } public static void main(String[] args) throws Exception { ReflectTest invokeTest = new ReflectTest(23); ReflectTest newinvokeTest = null; newinvokeTest = invokeTest.copy(invokeTest); System.out.println(newinvokeTest.getAge()); System.out.println(invokeTest.getClass().getConstructor(int.class).newInstance(11).getAge()); } }
本文參考了:http://www.blogjava.net/magibt/articles/161288.html?opt=admin