国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java反射簡單實例

2019-11-26 15:18:13
字體:
來源:轉載
供稿:網友

本文實例講述了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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 灵璧县| 蒙城县| 晋中市| 大石桥市| 晋城| 班玛县| 宾阳县| 景洪市| 揭西县| 延吉市| 新民市| 监利县| 司法| 柘荣县| 华容县| 民县| 广水市| 雅江县| 琼海市| 虞城县| 二连浩特市| 玛纳斯县| 庄河市| 洛川县| 晋宁县| 湖南省| 石泉县| 大埔区| 额济纳旗| 新竹市| 隆尧县| 广饶县| 陆良县| 阳西县| 商水县| 万安县| 托里县| 东安县| 江门市| 金昌市| 边坝县|