Java 用反射代替switch

写一个简单的计算器方法

package com.test;

public class Main {
	public static void main(String[] args) {
		calcul(23, 43, "sub");
	}
	
	public static void calcul(double arg0,double arg1,String type) {
		
		double result = 0;
		switch(type) {
		case "add":
			result = arg0 + arg1;
			break;
		case "sub":
			result = arg0 - arg1;
			break;
		case "mul":
			result = arg0 * arg1;
			break;
		case "div":	
			try {
				result = arg0 / arg1;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;

		}
		
		System.out.println(result);
		
	}
}

用反射代替switch

首先建立一个运算接口

package com.test;

public interface Calcul {
	double getResult(double arg0,double arg1);
}

然后几个具体运算类实现这个接口

package com.test;

public class Add implements Calcul {

	@Override
	public double getResult(double arg0, double arg1) {
		return arg0 + arg1;
	}

}

package com.test;

public class Sub implements Calcul {

	@Override
	public double getResult(double arg0, double arg1) {
		// TODO Auto-generated method stub
		return arg0 - arg1;
	}

}

package com.test;

public class Mul implements Calcul {

	@Override
	public double getResult(double arg0, double arg1) {
		// TODO Auto-generated method stub
		return arg0 * arg1;
	}

}

package com.test;

public class Div implements Calcul {

	@Override
	public double getResult(double arg0, double arg1) {
		// TODO Auto-generated method stub
		double ans = 0;
		try {
			ans = arg0 / arg1;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ans;
	}

}

最后去掉switch分支语句,通过反射机制来完成类的创建和方法的调用

package com.test;

public class Main {
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		calcul(23, 43, "Sub");
	}
	
	public static void calcul(double arg0,double arg1,String type) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		
		double result = 0;
		Class<?> clazz = Class.forName("com.test." + type);
		Calcul cal =  (Calcul) clazz.newInstance();
		
		result = cal.getResult(arg0, arg1);
		
		System.out.println(result);
		
	}
}


参考

你可能感兴趣的:(#,java)