在项目实践当中经常需要用到多个分支的需求,最常用的就是if/else结构,如果分支较多时,应该都能想到使用swich/case结构,但是有些时候分支太多,有几十个甚至上百个分支,这种情况下,再使用该结构处理,代码就显得有点不优雅了,也不利于项目的后期维护和升级,在java中用反射机制就能很好地解决此类问题,很优雅的去掉了所有的swcih/case结构。实现过程如下:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyTest {
private Position position;
public MyTest() {
System.out.println("调用了无参数构造函数");
}
public MyTest(Position position) {
System.out.println("调用了带参数构造函数");
this.position = position;
}
private void fun() {
System.out.println("调用了fun函数" + " pos: " + position.getX() +" "+position.getY());
}
private void mode() {
System.out.println("调用了mode函数");
}
@SuppressWarnings("all")
public static void main(String[] args) {
//包名
String classPath = "com.seandragon.";
//需要构造调用的类名
String[] className = {"MyTest"};
try {
Class curClass = Class.forName(classPath + className[0]);
//带参构造
Constructor constructor1 = curClass.getDeclaredConstructor(Position.class);
MyTest myTest1 = (MyTest) constructor1.newInstance(new Position(1,2));
Method method1 = curClass.getDeclaredMethod("fun");
//能否调用私有成员函数
method1.setAccessible(true);
method1.invoke(myTest1);
//无参默认构造
Object obj = curClass.newInstance();
Method method2 = curClass.getDeclaredMethod("mode");
//能否调用私有成员函数
method2.setAccessible(true);
method2.invoke(obj);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
System.out.println("此处接收被调用方法内部未被捕获的异常");
Throwable t = e.getTargetException();// 获取目标异常
t.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
public class Position {
//位置信息
private int x;
private int y;
public Position(int x,int y){
this.x = x;
this.y = y;
}
public Position(float x,float y){
this.x = (int) x;
this.y = (int) y;
}
public Position(){
x = 0;
y = 0;
}
public void set(int x,int y){
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
运行结果:


当Java项目中遇到分支过多的情况,传统的switch/case结构变得难以维护。通过反射机制,可以优雅地解决这个问题,简化代码并提高可维护性。文章介绍了如何使用反射来替换大量的switch/case,以实现更高效的代码结构。

3238

被折叠的 条评论
为什么被折叠?



