Java中switch-case优化方法之-----反射优化法

       在项目实践当中经常需要用到多个分支的需求,最常用的就是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优化方法之-----反射优化法_第1张图片

 

你可能感兴趣的:(Java,Android开发)