博客
关于我
反射跳转页面
阅读量:387 次
发布时间:2019-03-04

本文共 1267 字,大约阅读时间需要 4 分钟。

Intent intent2 = new Intent();                try {                    Class
clazz = Class.forName("com.example.liuan.test.TestActivity"); intent2.setClass(this, clazz); } catch(Exception e){ e.printStackTrace(); } startActivity(intent2);

【背景介绍】

  最近在进行公司项目开发时遇到这样一个需求:后台配置一个字段用于通知App跳转到相应的Activity。这个字段其实就是一个字符串用来表示是哪一个Activity。在实现初期,采用switch case的匹配机制,在Intent中设置对应的跳转二级页。这种实现方式的效果如下:

Intent intent = new Intent();switch (val) {    case "Acticity1":        intent.setClass(context, Acticity1.class);        break;    case "Acticity2":        intent.setClass(context, Acticity2.class);        break;    case "Acticity3":        intent.setClass(context, Acticity3.class);        break;    case "Acticity4":        intent.setClass(context, Acticity4.class);        break;    default:        break;}

  这里为了能够跳转到不同的二级页,增加了很多case判断,而且每次增加一个二级页,都需要改动原来的代码,显得非常不灵活。经过公司一位资深同事的指点,发现可以利用Java的反射机制高效解决这种问题,实现方案也异常优雅。

【解决方案】

Intent intent = new Intent();try {    Class
clazz = Class.ForName(val); intent.setClass(context, clazz);} catch(Exception e){ e.printStackTrace();}

  利用Java的反射机制,通过用户设置的跳转二级页类型的字符串类名,直接生成对应的class,用作Intent跳转的参数,这样可以有效优化代码逻辑,同时后续增加新的二级页也不用修改源代码直接进行跳转,显得异常灵活。 

转载地址:http://vnvr.baihongyu.com/

你可能感兴趣的文章
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>