注解基本信息
自定义注解及使用
定义注解
package com.hsh.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 定义注解 @ServiceAno * 保留到运行时,作用对象为方法 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ServiceAno { String service(); }
解析注解
package com.hsh.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ServiceAnoParser {
/*
* 解析注解,完成service的注入
*/
public static void setService(Object action) throws SecurityException,
NoSuchMethodException, ClassNotFoundException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException, InstantiationException{
Class<Action> clazz = (Class<Action>) action.getClass();
for(Field f : clazz.getDeclaredFields()){
for(Annotation ann : f.getDeclaredAnnotations()){
if(ann instanceof ServiceAno){
String methodName = getSetter(f.getName());
Method setter = clazz.getMethod(methodName, Service.class);
setter.setAccessible(true);
ServiceAno sa = (ServiceAno)ann;
String service = sa.service();
Class serClazz = Class.forName(service);
setter.invoke(action, serClazz.newInstance());
}
}
}
}
/**
* 生成set方法的方法名字符串
*/
public static String getSetter(String fieldName){
String name = "set";
name += (fieldName.charAt(0) + "").toUpperCase();
if(fieldName.length() > 1 ){
name += fieldName.substring(1);
}
return name;
}
}
使用注解
package com.hsh.annotation;
public interface Service {
public void service();
}
package com.hsh.annotation;
public class OracleService implements Service{
@Override
public void service(){
System.out.println("oracle service...");
}
}
package com.hsh.annotation;
public class MySqlService implements Service{
@Override
public void service(){
System.out.println("mysql service...");
}
}
package com.hsh.annotation;
public class Action {
//使用@ServiceAno 将MySqlService实例注入给mySqlService
@ServiceAno(service = "com.hsh.annotation.MySqlService")
private Service mySqlService;
//使用@ServiceAno 将OracleService实例注入给oracleService
@ServiceAno(service = "com.hsh.annotation.OracleService")
private Service oracleService;
public void service(){
mySqlService.service();
oracleService.service();
}
public Service getMySqlService() {
return mySqlService;
}
public void setMySqlService(Service mySqlService) {
this.mySqlService = mySqlService;
}
public Service getOracleService() {
return oracleService;
}
public void setOracleService(Service oracleService) {
this.oracleService = oracleService;
}
}
测试
package com.hsh.annotation;
public class Main {
public static void main(String[] args) {
Action action = new Action();
try {
ServiceAnoParser.setService(action);
action.service();
}catch (Exception e) {
e.printStackTrace();
}
}
}
测试结果