java反射簡略實例。本站提示廣大學習愛好者:(java反射簡略實例)文章只能為提供參考,不一定能成為您想要的結果。以下是java反射簡略實例正文
本文實例講述了java反射簡略完成辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:
package reflect;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
interface fruit{
public abstract void eat() ;
}
class Apple implements fruit{
public void eat() {
System.out.println("eat Apple");
}
}
class orange implements fruit{
public void eat() {
System.out.println("eat orange");
}
}
class init{
public static Properties getPro() throws FileNotFoundException, IOException{
Properties pro = new Properties() ;
File f = new File("fruit.properties") ;
if(f.exists()){
System.out.println("有設置裝備擺設文件!");
//從設置裝備擺設文件中讀取鍵值對
pro.load(new FileInputStream(f)) ;
}else{
System.out.println("沒有設置裝備擺設文件!");
pro.setProperty("apple", "reflect.Apple") ;
pro.setProperty("orange", "reflect.orange") ;
pro.store(new FileOutputStream(f), "FRUIT CLASS");
}
return pro ;
}
}
class Factory{
public static fruit getInstance(String className){
fruit f = null ;
try {
//經由過程反射獲得fruit的實例對象
f = (fruit)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return f ;
}
}
public class Hello {
public static void main(String[] args) {
try {
Properties pro = init.getPro() ;
fruit f = Factory.getInstance(pro.getProperty("apple")) ;
if(f != null){
f.eat() ;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
成果為:
有設置裝備擺設文件!
eat Apple
願望本文所述對年夜家的java法式設計有所贊助。