java反射簡單實例
本文實例講述了java反射簡單實現(xiàn)方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
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();
}
}
}
結(jié)果為:
有配置文件!
eat Apple
希望本文所述對大家的java程序設計有所幫助。
相關(guān)文章
Java?8?的異步編程利器?CompletableFuture的實例詳解
這篇文章主要介紹了Java?8?的異步編程利器?CompletableFuture?詳解,本文通過一個例子給大家介紹下Java?8??CompletableFuture異步編程的相關(guān)知識,需要的朋友可以參考下2022-03-03Java數(shù)組轉(zhuǎn)換為集合的相關(guān)方法
在Java中我們經(jīng)常需要將數(shù)組從一種類型轉(zhuǎn)換為另一種類型,下面這篇文章主要給大家介紹了關(guān)于Java數(shù)組轉(zhuǎn)換為集合的相關(guān)方法,文中通過圖文及代碼介紹的非常詳細,需要的朋友可以參考下2024-01-01Springboot報錯java.lang.NullPointerException: null問題
這篇文章主要介紹了Springboot報錯java.lang.NullPointerException: null問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11SpringBoot統(tǒng)一處理功能實現(xiàn)的全過程
最近在做項目時需要對異常進行全局統(tǒng)一處理,主要是一些分類入庫以及記錄日志等,下面這篇文章主要給大家介紹了關(guān)于SpringBoot統(tǒng)一功能處理實現(xiàn)的相關(guān)資料,文中通過圖文以及實例代碼介紹的非常詳細,需要的朋友可以參考下2023-03-03springboot集成mybatis?plus和dynamic-datasource注意事項說明
這篇文章主要介紹了springboot集成mybatis?plus和dynamic-datasource注意事項說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01