Q: How to ensure that code can be obfuscated, but reflection API benefits for action invoking could be used?

A: In JDK 5.0 solution exists, just use annotations.

So how to do such.

1) Define appropriate annotation

[code lang=”java”]
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Call {
int value();
}
[/code]

2) Define reflection action to use annotation definition

[code lang=”java”]
public class KCallAction extends KAction {

public KCallAction(int pID) {
super(pID);
}

@Override
public void actionPerformed(ActionContext pCtx)
{
final int id = getId();
final Window window = pCtx.getWindow();

for (Method method : window.getClass().getDeclaredMethods()) {
Call call = method.getAnnotation(Call.class);
if (call!=null && call.value()==id) {
try {
method.invoke(window, pCtx);
} catch (Exception e) {
LOG.error(”Call failed: ” + id, e);
}
break;
}
}
}

}
[/code]

3) Apply into actual use

[code lang=”java”]
public class CallFrame extends KApplicationFrame {

protected void createMenus() {
KMenu menu = new KMenu(TestConstants.R_MENU_FILE, new Action[] {
new KCallAction(TestConstants.R_OPEN)
});
setJMenuBar(new JMenuBar());
getJMenuBar().add(menu.create());
}

@Call(TestConstants.R_OPEN)
public void openFile(ActionContext pCtx) {
LOG.info(”OPENInvoke:” + pCtx);
}

public static void main(String[] pArgs) {
AppUtil.start(CallFrame.class, pArgs);
}

}
[/code]

4) Enjoy benefits!

/ java, Swing

Vastaa

Sähköpostiosoitettasi ei julkaista. Pakolliset kentät on merkitty *

This site uses Akismet to reduce spam. Learn how your comment data is processed.