面试题答案
一键面试-
定义自定义注解:
import kotlin.annotation.AnnotationTarget.FUNCTION @Retention(AnnotationRetention.SOURCE) @Target(FUNCTION) annotation class BusinessLogicEntry
-
编写注解处理器:
- 首先创建一个新的Java项目用于注解处理器(Kotlin编写注解处理器在Gradle配置上相对复杂,这里用Java示例,原理类似)。
- 引入必要的依赖,在
pom.xml
中添加:
<dependencies> <dependency> <groupId>com.google.auto.service</groupId> <artifactId>auto-service</artifactId> <version>1.0 - rc6</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin - annotations - common</artifactId> <version>${kotlin.version}</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin - compiler - embeddable</artifactId> <version>${kotlin.version}</version> </dependency> </dependencies>
- 编写注解处理器代码:
import com.google.auto.service.AutoService; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Set; @AutoService(Processor.class) @SupportedAnnotationTypes("BusinessLogicEntry") @SupportedSourceVersion(SourceVersion.RELEASE_8) public class BusinessLogicEntryProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element element : roundEnv.getElementsAnnotatedWith(BusinessLogicEntry.class)) { if (element.getKind() == ElementKind.METHOD) { String className = element.getEnclosingElement().getSimpleName().toString(); String methodName = element.getSimpleName().toString(); try (BufferedWriter writer = new BufferedWriter(new FileWriter("business_logic_config.txt", true))) { writer.write("Class: " + className + ", Method: " + methodName + "\n"); } catch (IOException e) { e.printStackTrace(); } } } return true; } }
-
在Kotlin项目中使用注解:
class MyClass { @BusinessLogicEntry fun myBusinessMethod() { // 业务逻辑代码 } }
以上代码展示了如何定义一个Kotlin自定义注解,并通过一个Java编写的注解处理器在编译期生成包含被注解方法信息的配置文件。实际使用中,注解处理器可能需要更复杂的处理逻辑和更好的错误处理机制,并且Gradle项目中使用Kotlin编写注解处理器需要正确配置Kotlin编译插件等。