物件映射範例 (Java Reflection)

主程式

package com.emprogria; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; public class BatchRule { public BatchRule() { } public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { Properties actionResult = new Properties(); Class<?> ceditRule = Class.forName("com.emprogria.CreditRule"); Constructor<?> consCeditRule = ceditRule .getConstructor(java.util.Properties.class); Object objCeditRule = consCeditRule.newInstance(actionResult); Class<?>[] paramInteger = { Integer.TYPE }; Method checkRuleOfCeditRule = ceditRule.getDeclaredMethod("checkRule", paramInteger); checkRuleOfCeditRule.invoke(objCeditRule, 28); System.out.println(actionResult.getProperty("CreditRule")); } }

調用類別程式

package com.emprogria; import java.util.Properties; public class CreditRule { private Properties actionResult = null; private int creditLevel = 0; public CreditRule() { super(); } public CreditRule(Properties actionResult) { super(); this.actionResult = actionResult; } public void checkRule(int age) { if (age < 15) { this.creditLevel = 0; } else if (age < 20) { this.creditLevel = 1; } else if (age < 25) { this.creditLevel = 2; } else if (age < 30) { this.creditLevel = 3; } else if (age < 40) { this.creditLevel = 4; } else { this.creditLevel = 5; } try { if (this.actionResult != null) { synchronized (this.actionResult) { this.actionResult.put("CreditRule", String.valueOf(this.creditLevel)); } } } catch (Exception e) { e.printStackTrace(); } } }