zoukankan      html  css  js  c++  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

  • 相关阅读:
    SQL Server(00):约束Constraint
    SQL Server(00):T-SQL批处理
    SQL Server(00):事务
    SQL Server(00):锁
    SQL Server(00):表变量和临时表
    SQL Server(00):T-SQL游标
    SQL Server(00):用户自定义函数(UDF)
    SQL Server(00):存储过程Stored Procedure
    C#(99):微软报表A4纸大小规则
    C#(99):C#互操作
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4022136.html
Copyright © 2011-2022 走看看