2014-10-03 5 views
1

Im는 안드로이드 프로젝트를위한 주석 프로세서를 작성하고 있습니다. 나는 안드로이드 리소스 폴더의 절대 경로를 얻고 싶습니다 (나는 gradle을 통해 구성 가능하다는 것을 알고 있지만, 지금은이 경우를 무시합니다). 작업 디렉토리의 파일 경로를 얻으십시오

@MyAnnotation public class Foo{ ... } 

그래서 내 AnnotationProcessor에 내가 Foo.java의 경로를 얻으려면 :

내 생각은 처리 요소의 절대 경로를 얻을 수 있습니다.

@Override public boolean process(Set<? extends TypeElement> annotations, 
     RoundEnvironment roundEnv) { 

    for (Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) 

     try { 
     ProcessorMessage.info(element, "Path: %s %s", getWorkingDir(), getExecutionPath()); 
     } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
     ProcessorMessage.error(element, "Error " + e.getMessage()); 
     } 

    return false; 
    } 

    private String getExecutionPath() throws UnsupportedEncodingException { 
    String path = AnnotatedAdapterProcessor.class.getProtectionDomain() 
     .getCodeSource() 
     .getLocation() 
     .getPath(); 
    String decodedPath = URLDecoder.decode(path, "UTF-8"); 

    return decodedPath; 
    } 

    private String getWorkingDir() { 
    Path currentRelativePath = Paths.get(""); 
    String s = currentRelativePath.toAbsolutePath().toString(); 
    return s; 
    } 

이 나에게 다음과 같은 출력을 제공하지만 :

경로 : /Users/XXXXX/.gradle/daemon/1.12 /Users/XXXXX/.m2/repository/com/example/myprocessor/processor/ 0.1.2-SNAPSHOT/processor-0.1.2-SNAPSHOT.jar

Foo.java이있는 경로를 얻을 수있는 방법이 있습니까? (리소스 폴더를 계속 검색 할 시작 지점을 얻으려고)

답변

0

이러한 경로는 아마도 사용자의 빌드 환경에 달려 있다고 생각합니다. 수동으로 구성하면 모든 컴퓨터에서 작동하지 않을 수도 있습니다 머신 또는 모든 IDE에서. 그게 내가 당신이 바른 길에 아직도 생각 작동하지 않는 경우 Annotation processor, get project path

을하지만,이처럼 프로세서에 의해로드 된 클래스 대신 실제 자원을 사용하여 시도해야합니다 :
이 질문은 도움이 될 수

을 이 모든 또한 프로세서의 맥락에서 적용되는 경우
String path = Foo.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 

는 잘 모르겠지만, 일반적으로 이것은 당신에게 클래스 파일의 루트 출력 디렉토리를 제공해야합니다 :

String path = Foo.class.getClassLoader().getResource(".").getFile(); 

당신이 알고 있다면 그쪽을 예를 들어 출력 디렉토리가 your_project/target/classes이면 소스 또는 자원 디렉토리로 가져올 수 있습니다.