我的博客网站:http://www.zeromike.net/
本文地址:http://www.zeromike.net/?p=48
反射的一种使用场景是业务代码里有很多不同的方法,通过客户端传入方法名称和参数调用执行业务方法。我这里只写出示意性代码,下篇我会写phonegap插件怎么写。
1.注解代码
?
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)//表示注解的信息被保留在class文件(字节码文件)中当程序编译时,会被虚拟机保留在运行时
@Target(ElementType.METHOD)//说明该注解只能被声明在一个类的方法前
public @interface MyAnnontion {
}
?
2.业务代码
public class MyTest {
@MyAnnontion
public void sendMessage(String message){
System.out.println("send Message..."+message);
}
@MyAnnontion
public void findAll(){
System.out.println("find all...");
}
}
?
3.测试代码
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyMain {
public static void main(String[] args) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Method[] method = MyTest.class.getMethods();
MyTest test = new MyTest();
for (Method m : method) {
MyAnnontion annotation = m.getAnnotation(MyAnnontion.class);// 获得当前方法注解
if (annotation != null) {
int isParam = m.getParameterTypes().length;// 判断是否有参数
if (isParam == 0) {
m.invoke(test);
} else {
m.invoke(test, new Object[] { "abc" });
}
}
}
}
}
?
?
结果:
?
find all...
send Message...abc
?
原文链接:http://www.zeromike.net/?p=48
原文作者:zeromike
原文:http://zhangzhaoaaa.iteye.com/blog/2150992