자바 annotation processing 자동 생 성 코드

1457 단어
package example;

import java.io.*;
import javax.tools.*;
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;

@SupportedAnnotationTypes(value = { "*" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class ExampleProcessor extends AbstractProcessor {

	private Filer filer;

	public void init(ProcessingEnvironment env) {
		filer = env.getFiler();
	}

	public boolean process(Set elements, RoundEnvironment env) {
		// Discover anything marked with @SuppressWarnings
		for (Element element : env
				.getElementsAnnotatedWith(SuppressWarnings.class)) {
			if (element.getKind() == ElementKind.METHOD) {
				// For any methods we find, create an aspect:
				String methodName = element.getSimpleName().toString();
				String aspectText = "public aspect Advise_" + methodName
						+ " {
" + " before(): execution(* " + methodName + "(..)) {
" + " System.out.println(\"" + methodName + " running\");
" + " }
" + "}
"; try { JavaFileObject file = filer.createSourceFile("Advise_" + methodName, element); file.openWriter().append(aspectText).close(); System.out.println("Generated aspect to advise " + methodName); } catch (IOException ioe) { } } } return true; } }

좋은 웹페이지 즐겨찾기