类对象:Class classObj;
问题:如何动态创建Role实例或Dept实例

解决方案 »

  1.   

    Object obj = classObj.newInstance();
      

  2.   

    是这样的:
    public void methods(Class classObj){
          //我现在需要通过这个classObj对象来创建实例,传进来有可能是Role类的类对象,也有可能是Dept类的类对象。现在我需要创建实例。有可能会创建Role类实例,有可能会创建Dept类实例}
      

  3.   


    if (classObj instanceof Role) {
        Class<?> f = Class.forName("Role");
        f.newInstance();
    }
    if (classObj instanceof Dept) {
        Class<?> f = Class.forName("Dept");
        f.newInstance();
    }
      

  4.   

    classObj 应该是Role和Dept的接口或者父类
      

  5.   

    public class Test2 {
    public static void main(String[] str) {
    try {
    Class c = Class.forName("Role");
    Role r = (Role)c.newInstance();
    r.m();
    c = Class.forName("Dept");
    Dept d = (Dept)c.newInstance();
    d.m();
    }catch(Exception e) {
    e.printStackTrace();
    }
    }
    }class Role {
    Role(){System.out.println("Role类的构造方法!");};
    public void m() {
    System.out.println("Role类的成员方法!");
    }
    }class Dept {
    Dept(){System.out.println("Dept类的构造方法!");};
    public void m() {
    System.out.println("Dept类的成员方法!");
    }
    }/*
    结果:
    Role类的构造方法!
    Role类的成员方法!
    Dept类的构造方法!
    Dept类的成员方法!
    */
      

  6.   


    如果有instanceof的话应该就OK了
      

  7.   

    通过Class对象可以得到类名,判断类名,然后再去创建对象好了.
    String name=classObj.getName();
    if(name.equals(xxx))
    {}else if(name.equals(uuu))
    {}
      

  8.   

    //不是很明白你的意思
    //通过 instanceof 判断后可直接转换成需要的对象
    //或通过Class.forName() 新建一个需要的对象package upc;public class test
    {
    public static void main(String[] args) {
    test t=new test();
    t.methods(new Role());//传入一个Role实例
    System.out.println("----------------");//分隔线
    t.methods(new Dept());//传入一个Dept实例
    }

    public void methods(Object obj){

    //判断obj对象是否为Role类
    if(obj instanceof Role){
                            //直接将obj对象强制转换成Role对象
    Role r = (Role)obj;
    r.getMsg();//第一次输出in the Role class

    //创建新的Role类实例
    try{
    //得到类全名
    String strName=obj.getClass().getName();
    //创建新的Role类对象
    Role role=(Role)Class.forName(strName).newInstance();
    role.getMsg();//第二次输出in the Role class
    }catch(Exception ee){
    }
    }

    //判断obj对象是否为Dept类
    if(obj instanceof Dept){
                            //直接将obj对象强制转换成Dept对象
    Dept d = (Dept)obj;
    d.getMsg();//第一次输出in the Dept class

    //创建新的Dept类实例
    try{
    //得到类全名
    String strName=obj.getClass().getName();
    //创建新的Role类对象
    Dept dept=(Dept)Class.forName(strName).newInstance();
    dept.getMsg();//第二次输出in the Dept class
    }catch(Exception ee){
    }
    }
    }
    }class Role
    {
    public void getMsg(){
    System.out.println("in the Role class");
    }
    }class Dept
    {
    public void getMsg(){
    System.out.println("in the Dept class");
    }
    }/*输出结果:
    in the Role class
    in the Role class
    ----------------
    in the Dept class
    in the Dept class
    */