最近在学习Anntation和Reflection,一直希望能做一个实际的应用.
所以,假象了一个例子,比如说在方法前加上Annotation来表明方法是否要进行事务处理,然后通过动态代理来执行.
1 MyAnnotationI
java 代码
- public interface MyAnnotationI {
- public void printString();
- public void printString1();
- }
2
java 代码
- public class MyAnnotationImpl implements MyAnnotationI {
- @MyAnnotation(isTransaction ="yes")
- public void printString() {
- System.out.print("\n"+" don some thing");
- }
- @MyAnnotation(isTransaction="yes")
- public void printString1() {
- System.out.print("\n"+" good work");
- }
- }
3 然后是定义的Annotation
java 代码
- @Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
- public @interface MyAnnotation {
- String isTransaction();
- }
我希望能在执行 MyAnnotationImpl 的;两个方法是做一个判断,来看是否执行事务代码. 下面是我写的代理类
java 代码
- public class MyHandler implements InvocationHandler {
- private Object o;
- public MyHandler(Object delegate) {
- o = delegate;
- }
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Object a = null;
- try{
- System.out.print("\n"+"Start transaction ");
- a = method.invoke(o, args);
- System.out.print("\n"+"end transaction ");
- }
- catch(Exception e)
- {
- System.out.print("\n"+"Exception");
- }
- return null;
- }
- }
也就是希望在方法上有isTransaction ="yes"的方法前后执行两行代码.
下面是运行代码
java 代码
- public class MyAnnotationTest {
- public void dynamicProxy()
- {
- }
- public static void main(String[] args) {
- try {
- Class bean = Class.forName("com.my.annotation.one.MyAnnotationImpl");
- Method method[] = bean.getMethods();
- for (int i = 0; i < method.length; i++) {
- if (method[i].getName().equals("printString1")) {
- MyAnnotation an = method[i].getAnnotation(MyAnnotation.class);
- if(an.isTransaction().equals("yes"))
- {
- Object o = bean.newInstance();
- InvocationHandler handler = new MyHandler(bean.newInstance());
- MyAnnotationI proxy = (MyAnnotationI) Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(),
- handler);
- Method m = proxy.getClass().getDeclaredMethod("printString1", null);
- m.invoke(proxy, new Object[]{});
- }
- }
- }
- } catch (Exception e) {
- System.out.println(e.toString());
- }
- }
- }
输出结果如下:
Start transaction
good work
end transaction
这样看似通过Annotation和Reflection 实现了一个事物,但是我有些问题.
1 这里是我指明了要调用哪个方法的,如果我也不知道具体执行那个方法.需要在运行时动态的去判定,我该怎么做?
2 我在 proxy.getClass().getDeclaredMethod("printString1", null)中调用的无参数的方法,如果我的执行方法有参数, 程序怎么知道有那些 参数,如果得到要调用的方法?
希望明白的朋友给我指点一二.