【案例1】經過一個對象得到完整的包名和類名java
- 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類對象ide
- 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());
- }
- }
- 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));
- }
- }
【案例3】經過Class實例化其餘類的對象函數
經過無參構造實例化對象this
- 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(int age) {
- 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]code
可是注意一下,當咱們把Person中的默認的無參構造函數取消的時候,好比本身定義只定義一個有參數的構造函數以後,會出現錯誤:
好比我定義了一個構造函數:對象
- 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建立其餘類的對象)
- 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, int age) {
- 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]
【案例】
返回一個類實現的接口:
- 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的代碼)
【案例】:取得其餘類中的父類
- 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.*;
而後將主類編寫爲:
- 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這一類的修飾符
下面這個例子咱們就來獲取修飾符
- 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){}
有時候一個方法可能還有異常,呵呵。下面看看:
- 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取得一個類的所有框架
- 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;
【案例】其實還能夠經過反射調用其餘類中的方法:
- 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方法
- 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
【運行結果】:
男