反射的使用总结

反射:

优缺点:性能会降低;

maven:


    org.reflections
    reflections
    0.9.11

使用的示例:

eg(实现同一接口,调用对应的具体实现类的某个方法):

Reflections reflections = new Reflections("com.ximalaya.mulehorse.client.selector");
Set> allClasses =
        reflections.getSubTypesOf(Selector.class);
for (Class selector : allClasses) {
    if (unused_selectors.contains(selector.getSimpleName())) {
        continue;
    }
    SelectorDescriptor selectorDescriptor = Reflect.on(selector).create().call("toSelectorDescriptor").get();
    selectorDisNameMap.put(selectorDescriptor.getDisName(), selectorDescriptor.getName());

    selectorNameMap.put(selectorDescriptor.getName(), selector.getName());

    map.put(selectorDescriptor.getName(), selectorDescriptor);
}
public class Selectors {



    private static Set unused_selectors = Sets.newHashSet("DefaultSelector", "KeywordSelector");

    public static final Map selectorNameMap = new HashMap();

    public static final Map selectorDisNameMap = new HashMap();

    public final static Map map = new HashMap();



    static {
        Reflections reflections = new Reflections("com.ximalaya.mulehorse.client.selector");
        Set> allClasses =
                reflections.getSubTypesOf(Selector.class);
        for (Class selector : allClasses) {
            if (unused_selectors.contains(selector.getSimpleName())) {
                continue;
            }
            SelectorDescriptor selectorDescriptor = Reflect.on(selector).create().call("toSelectorDescriptor").get();
            selectorDisNameMap.put(selectorDescriptor.getDisName(), selectorDescriptor.getName());

            selectorNameMap.put(selectorDescriptor.getName(), selector.getName());

            map.put(selectorDescriptor.getName(), selectorDescriptor);
        }
    }

    public static SelectorDescriptor getSelector(String selectorName) {
        return map.get(selectorName);
    }

    public static final String getDisName(String selectorName) {
        SelectorDescriptor selectorDescriptor = map.get(selectorName);
        Preconditions.checkNotNull(selectorDescriptor);
        return selectorDescriptor.getDisName();
    }

    public static final String getParameterDisName(String selectorName) {
        SelectorDescriptor selectorDescriptor = map.get(selectorName);
        Preconditions.checkNotNull(selectorDescriptor);
        return selectorDescriptor.getParameterDisName();
    }
}

 

public interface Selector {

    List getVersion(Object request);

    String getSelectorName();

    SelectorDescriptor toSelectorDescriptor();

}

 

 

你可能感兴趣的:(coreJava,javaweb)