在Java中,注解(Annotation)是一种元数据形式,它提供了一种将元数据与程序元素(类、方法、变量等)关联起来的方式。虽然注解本身并不直接实现代码复用,但它们可以与代码生成工具、框架和库结合使用,从而间接地促进代码复用。以下是一些使用Java注解实现代码复用的方法:
@LogExecutionTime的注解,用于记录方法的执行时间。import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}
@Around通知来实现在方法执行前后记录执行时间。import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
@Aspect
public class LogExecutionTimeAspect {
@Around("@annotation(LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
System.out.println(joinPoint.getSignature() + " executed in " + (endTime - startTime) + " ms");
return result;
}
}
@Getter和@Setter注解来自动生成Java类的getter和setter方法。import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class User {
private String name;
private int age;
}
总之,虽然注解本身并不直接实现代码复用,但它们可以与AOP、代码生成工具等结合使用,从而间接地促进代码复用。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。