huanxuan163 2017-03-13 13:08 采纳率: 0%
浏览 957
已采纳

请问这段java代码怎么重构?就是想要实现动态传入类型

    if("student".equals(type)){
        Student student=new Student();
        student.setAccount(account);
        student.setPassword(password);
        student.setCreateTime(new Date());
        studentService.save(student);
    }else if("labor".equals(type)){
        Labor labor=new Labor();
        labor.setAccount(account);
        labor.setPassword(password);
        labor.setCreateTime(new Date());
        laborService.save(labor);
    }else if("manager".equals(type)){
        Manager manager=new Manager();
        manager.setAccount(account);
        manager.setPassword(password);
        manager.setCreateTime(new Date());
        managerService.save(manager);
    }else if("xuegong".equals(type)){
        XueGong xueGong=new XueGong();
        xueGong.setAccount(account);
        xueGong.setPassword(password);
        xueGong.setCreateTime(new Date());
        xueGongService.save(xueGong);
    }
  • 写回答

1条回答 默认 最新

  • threenewbee 2017-03-13 13:11
    关注
     反射
    http://blog.csdn.net/smartboy_01/article/details/23201391
    为了简单,可定义一个接口,包括setAccount setPassword等方法
    Class classType = Class.forName("类名");  
    接口 obj = (接口)classType.newInstance();  
    obj.setAccount()
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已采纳回答 10月11日

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn