java中通过类名实例化类

String className ="test.Test1";
        Class clazz;
        try {
            clazz = Class.forName(className);
            Test1 userDao=(Test1) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
这里className必须是完整的包名类名,另外这种方式通过Test1的这种方式进行实例化:
public Test1(){
        System.out.println("new Test1");
    }

 

posted @ 2015-09-06 17:51  QG_Li  阅读(3430)  评论(0编辑  收藏  举报