java反射機制基礎

//LearnReflect.java
package cn.itcast.reflect;


import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;

public class LearnReflect {

/**
* @param args
* @throws Exception 
* @throws InstantiationException 
*/
public static void main(String[] args) throws InstantiationException, Exception {
MainCard man=new MainCard();
/*
* 原來舊的方法
*/
man.harddisk();
man.memory();

/*
* 擴展後加入的類和方法
*/
//讀取配置文件
File file=new File("pci.properties");
FileInputStream fis=new FileInputStream(file);
Properties properties=new Properties();
/*
* 加載流
*/
properties.load(fis);
String pciname=null;
/*
* 循環讀取配置文件的信息
*/
for(int i=1;i<=properties.size();i++)
{
pciname=properties.getProperty("pci"+i);
OutRun(man, pciname);
}
fis.close();


}

/*
* 擴展類方法的使用
*/
private static void OutRun(MainCard man, String pciname) throws Exception {
Class clazz=Class.forName(pciname);
PCI pci=(PCI)clazz.newInstance();
/*
* 使用實現了PCI藉口的類的方法
*/
man.runPCI(pci);
/*
* 有參函數的的調用
*/
Method method=clazz.getMethod("hello", String.class);
/*
* 創建一個默認的構造函數對象
*/
Object obj=clazz.newInstance();
/*
* 函數的調用和參數的注入
*/
method.invoke(obj, "Hello World!");

//設置字段的值
Field field=clazz.getDeclaredField("name");
field.set(obj, "張三");

/*還有很多
* 1、獲取字段
*指定字段(無論是public,protect或private)的獲取和賦值
*get.getDeclaredField("name")
*get.getDeclaredFields();
*還有get.getFiled("name");獲取指定public的字段
*還有get.getFileds();獲取所有public的字段
*2、獲取方法
*指定方法(無論是public,protect或private)的獲取和賦值
*get.getDeclaredMethod("name");
*獲取所有的方法(無論是public,protect或private)
*get.getDeclaredMethods();
*還有get.getMethod("name");獲取指定public的字段
*還有get.getMethods();獲取所有public的字段
*3、獲取構造函數
*
*getDeclaredConstructor(Class<?>... parameterTypes)
*/
}
}

//MainCard.java

package cn.itcast.reflect;


public class MainCard {


public void harddisk()
{
System.out.println("harddisk  running ....");
}
public void memory()
{
System.out.println("memery  running.....");
}

public void runPCI(PCI pci)
{
pci.sound();
pci.look();
}

}

//SoundCard.java

package cn.itcast.reflect;


public class SoundCard implements PCI{


private String name;
public String heheString;
@Override
public void look() {
System.out.println("look  running....");

}


@Override
public void sound() {
System.out.println("sound  running....");

}

public void  hello(String string){
System.out.println("Say" +string+ "to you !");
}



}


//pci.properties配置文件
pci1=cn.itcast.reflect.SoundCard


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章