当前位置: 代码迷 >> Web前端 >> java中的反照机制
  详细解决方案

java中的反照机制

热度:329   发布时间:2012-06-27 14:20:09.0
java中的反射机制
怎样在java中通过类的名字来加载这个类的对象,需要使用到java中的反射机制:

  如:通过Properties文件来读取这个类名
  calss MyFactory
{
   Student student;
   Properties prop=new Properties();
   //类加载器可以从classPath中加载文件 ,在src文件夹下就可以被加载
   //因为这个会被编译成class文件放在bin目录下载
   InputStream inStream=MyFactory.class.getClassLoader()
    .getResourceAsStream("myproperties.properties");
   prop.load(inStream);
   //studentKey是放在properties文件中的Key
    String studentValue=prop.getProperty("studentKey");//Student
    //这个Class.forName("studentValue")只是在虚拟机中装载这个类,没有实例 
     //对 象
     //实例对象=(Student)Class.forName("studentValue").NewInstance();
    //这里必须保证这个类中有一个无参的构造函数
    student=(Student)Class.forName("studentValue").NewInstance();
}
  相关解决方案