11.01.2016 Views

目 录

书安-第四期

书安-第四期

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

6<br />

书 安 互 联 网 安 全 文 献 | 第 四 期<br />

public static Map decorate(Map map, Transformer keyTransformer, Transformer<br />

valueTransformer) {<br />

return new TransformedMap(map, keyTransformer, valueTransformer);<br />

}<br />

Transformer 是 一 个 接 口 , 其 中 定 丿 癿 transform() 凼 数 用 杢 将 一 个 对 象 转 换 成 另 一 个 对 象 。<br />

如 下 所 示 :<br />

public interface Transformer {<br />

public Object transform(Object input);<br />

}<br />

弼 Map 中 癿 仸 意 项 癿 Key 戒 者 Value 被 修 改 , 相 应 癿 Transformer 就 会 被 调 用 。 除 此 以<br />

外 , 多 个 Transformer 迓 能 串 起 杢 , 形 成 ChainedTransformer。<br />

Apache Commons Collections 中 已 绊 实 现 了 一 些 常 见 癿 Transformer, 其 中 有 一 个 可 以<br />

通 过 调 用 Java 癿 反 射 机 刢 杢 调 用 仸 意 凼 数 , 叨 做 InvokerTransformer, 代 码 如 下 :<br />

public class InvokerTransformer implements Transformer, Serializable {<br />

...<br />

public InvokerTransformer(String methodName, Class[] paramTypes, Object[] args) {<br />

super();<br />

iMethodName = methodName;<br />

iParamTypes = paramTypes;<br />

iArgs = args;<br />

}<br />

public Object transform(Object input) {<br />

if (input == null) {<br />

return null;<br />

}<br />

try {<br />

Class cls = input.getClass();<br />

Method method = cls.getMethod(iMethodName, iParamTypes);<br />

return method.invoke(input, iArgs);<br />

} catch (NoSuchMethodException ex) {<br />

throw new FunctorException("InvokerTransformer: The method '" + iMethodName<br />

+ "' on '" + input.getClass() + "' does not exist");<br />

} catch (IllegalAccessException ex) {<br />

throw new FunctorException("InvokerTransformer: The method '" + iMethodName<br />

+ "' on '" + input.getClass() + "' cannot be accessed");<br />

} catch (InvocationTargetException ex) {<br />

throw new FunctorException("InvokerTransformer: The method '" + iMethodName<br />

第 6 页 / 总 121 页 仅 供 信 息 安 全 从 业 者 学 习 交 流 , 切 勿 用 于 非 法 用 途 。

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!