java反射简单实例
本文实例讲述了java反射简单实现方法。分享给大家供大家参考。具体实现方法如下:
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程序设计有所帮助。
上一篇: JAVA JDK8 List获取属性列表