映射_方法调用

xiaoxiao2026-04-20  9

java的反映机制提供了调用方法的方法.在非映射代码中,如果不实例化就无法调用(非静态)方法.映射机制提供了java.lang.reflect.Method.invoke()方法.如下示例: import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.Type;import java.util.Locale;import static java.lang.System.out;import static java.lang.System.err;public class Deet<T> { private boolean testDeet(Locale l) { out.format("Locale = %s, ISO Language Code = %s%n", l.getDisplayName(),l.getISO3Language()); return true; } private int testFoo(Locale l) {return 0;} private boolean testBar() {return true;} public static void main(String... args) { if(args.length !=4) { err.format("Usage:java Deet <classname> <language> <country> <variant>%n"); return; } try { Class<?> c = Class.forName(args[0]); Object t = c.newInstance(); Method[] allMethods = c.getDeclaredMethods(); for(Method m : allMethods) { String mname = m.getName(); if(!mname.startsWith("test") ||(m.getGenericReturnType() != boolean.class)) { continue; } Type[] pType = m.getGenericParameterTypes(); if((pType.length != 1) || Locale.class.isAssignableFrom(pType[0].getClass())) { continue; } out.format("invoking %s()%n", mname); try{ m.setAccessible(true); Object o = m.invoke(t,new Locale(args[1],args[2],args[3])); out.format("%s() return %b%n",mname,(Boolean) o); } catch(InvocationTargetException x) { Throwable cause = x.getCause(); err.format("invocation of %s failed: %s %n", mname,cause.getMessage()); } }//for }catch(ClassNotFoundException x) { x.printStackTrace(); }catch(InstantiationException x) { x.printStackTrace(); }catch(IllegalAccessException x) { x.printStackTrace(); } }} 相关资源:敏捷开发V1.0.pptx
转载请注明原文地址: https://www.6miu.com/read-5047665.html

最新回复(0)