생성 된 코드와 같은 특정 디렉토리 또는 파일에 대한 Java 경고를 표시하지 않는 방법
다소 추한 코드를 생성하는 파서 생성기를 사용하고 있습니다. 결과적으로 Eclipse 프로젝트에는 생성 된 소스 파일에서 발생하는 수십 개의 경고가 있습니다. @SuppressWarning
주석을 사용하여 특정 요소의 특정 경고를 억제 할 수는 있지만 파서 생성기가 다시 실행될 때 직접 추가하는 주석이 손실됩니다. 특정 파일이나 디렉토리에 대한 경고를 표시하지 않도록 Eclipse를 구성하는 방법이 있습니까?
버전 3.8 M6부터 Eclipse (정확하게 : JDT)에는이를위한 기능이 내장되어 있습니다. 프로젝트의 빌드 경로 ( 프로젝트 속성> Java 빌드 경로> 컴파일러> 소스)를 통해 구성 할 수 있습니다.
여기 발표 : 이클립스 3.8 및 4.2 M6 - 신규 및 주목할만한 라는 선택적으로 소스 폴더에서 오류 / 경고를 무시 . 스크린 샷의 출처이기도합니다. 이것은 이전에 링크 된 버그 220928 에서 개발 된 새로운 기능입니다 .
Eclipse 3.8 용으로 완성 된 Bug 220928 티켓이 있습니다. 자세한 내용은 이 답변 을 참조하십시오.
Eclipse 3.7 이하를 사용하는 경우 : 해당 티켓에 대해 "Marc"사용자가 주석 35 에서 'warningcleaner'라는 플러그인을 작성했거나 적어도 링크했습니다 . 이 기능이 Eclipse에 통합되기를 기다리는 동안 많은 성공을 거두어 사용하고 있습니다.
정말 간단합니다 :
- 플러그인을 설치하십시오.
- 프로젝트를 마우스 오른쪽 단추로 클릭하고 "생성 된 코드 특성 추가 / 제거"를 선택하십시오.
- 프로젝트 설정을여십시오 (마우스 오른쪽 버튼을 클릭하고 "속성"을 선택하십시오).
- '경고 클리너'탭을여십시오.
- 경고를 무시하려는 소스 폴더를 선택하십시오.
maven regexp replace 플러그인을 사용하여 이것을 해결했습니다. 원인을 해결하지는 않지만 고통을 치유합니다.
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>maven-replacer-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<includes>
<include>target/generated-sources/antlr/**/*.java</include>
</includes>
<regex>true</regex>
<regexFlags>
<regexFlag>MULTILINE</regexFlag>
</regexFlags>
<replacements>
<replacement>
<token>^public class</token>
<value>@SuppressWarnings("all") public class</value>
</replacement>
</replacements>
</configuration>
</plugin>
** 표기법이 작동하지 않았으므로 경로를 정확하게 지정해야 할 수도 있습니다.
중복 @SupressWarnings를 생성하지 않는 방법에 대한 개선 사항은 아래 주석을 참조하십시오
경고를 표시하기 위해 프로젝트 별 설정을 활성화하는 것이 최선이라고 생각합니다.
창-> 환경 설정-> Java-> 컴파일러-> 오류 / 경고
양식 상단에는 프로젝트 별 설정 구성을위한 링크가 있습니다.
사용자 @Jorn은 Ant 코드에서 힌트를주었습니다. 여기 내가 가진 것
<echo>Adding @SuppressWarnings("all") to ANTLR generated parser/lexer *.java</echo>
<echo> in ${project.build.directory}/generated-sources/antlr/</echo>
<replace dir="${project.build.directory}/generated-sources/antlr/"
summary="true"
includes="**/*.java"
token="public class"
value='@SuppressWarnings("all") public class' />
Note that Ant's <replace> does text replacement, not regular expression replacement, so it cannot use the ^ meta-character in the token to match beginning of line as the maven regexp replace plugin does.
I'm doing this at the same time that I run Antlr from maven-antrun-plugin in my Maven pom, because the ANTLR maven plugin did not play well with the Cobertura maven plugin.
(I realize this is not an answer to the original question, but I can't format Ant code in a comment/reply to another answer, only in an answer)
I don't think Eclipse inherently provides a way to do this at the directory level (but I'm not sure).
You could have the generated files go into a separate Java project, and control warnings for that specific project.
I generally prefer to place automatically-generated code in a separate project anyway.
You can only suppress warnings at the project level. However, you can configure your problems tab to suppress warnings from files or packages. Go into the Configure Contents menu and work with the "On working set:" scope.
I'm doing this to a few ANTLR grammars, which generate a Java parser using Ant. The Ant build script adds the @SuppressWarnings("all")
to one Java file, and @Override
to a few methods in another. I can look up how it's done exactly, if you're interested.
This small python script "patches" the M2E-generated .classpath
files and adds the required XML tag to all source folders starting with target/generated-sources
. You can just run it from you project's root folder. Obviously you need to re-run it when the Eclipse project information is re-generated from M2E. And all at your own risk, obviously ;-)
#!/usr/bin/env python
from xml.dom.minidom import parse
import glob
import os
print('Reading .classpath files...')
for root, dirs, files in os.walk('.'):
for name in files:
if (name == '.classpath'):
classpathFile = os.path.join(root, name)
print('Patching file:' + classpathFile)
classpathDOM = parse(classpathFile)
classPathEntries = classpathDOM.getElementsByTagName('classpathentry')
for classPathEntry in classPathEntries:
if classPathEntry.attributes["path"].value.startswith('target/generated-sources'):
# ensure that the <attributes> tag exists
attributesNode = None;
for attributes in classPathEntry.childNodes:
if (attributes.nodeName == 'attributes'):
attributesNode = attributes
if (attributesNode == None):
attributesNode = classpathDOM.createElement('attributes')
classPathEntry.appendChild(attributesNode)
# search if the 'ignore_optional_problems' entry exists
hasBeenSet = 0
for node in attributesNode.childNodes:
if (node.nodeName == 'attribute' and node.getAttribute('name') == 'ignore_optional_problems'):
# it exists, make sure its value is true
node.setAttribute('value','true')
#print(node.getAttribute('name'))
hasBeenSet = 1
if (not(hasBeenSet)):
# it does not exist, add it
x = classpathDOM.createElement("attribute")
x.setAttribute('name','ignore_optional_problems')
x.setAttribute('value','true')
attributesNode.appendChild(x)
try:
f = open(classpathFile, "w")
classpathDOM.writexml(f)
print('Writing file:' + classpathFile)
finally:
f.close()
print('Done.')
In the case of ANTLR 2, it is possible to suppress warnings in generated code by appenidng @SuppressWarnings
before the class declaration in the grammar file, e.g.
{@SuppressWarnings("all")} class MyBaseParser extends Parser;
This can be done by excluding certain directories from the build path (The following example is given using Eclipse 3.5)
[1] Bring up the Java Build Path
- Click on the projectin Package Explorer
- Right click, properties
- Select Java Build Path
[2] Add directories to exclude
- The Source tab should contain details of the project source folders
- Expand the source folder and locate the 'Excluded:' property
- Select 'Excluded:' and click Edit
- Add folders into the Exclusion patterns using the Add/Add Multiple options
- Click Finish, then ok for Eclipse to rebuild.
경고 클리너 플러그인을 출시 한 지 오래되었습니다. 이제 Eclipse 3.8을 사용하고 있으므로 더 이상 필요하지 않습니다. 그러나 여전히이 플러그인이 필요한 사람들을 위해 bintray의 업데이트 사이트와 함께 github에서 릴리스했습니다. 여전히 Eclipse 3.7 또는 그 이전 버전을 사용중인 경우 유용 할 수 있습니다. 설치 세부 사항은 이 사이트 를 확인 하십시오.
'programing tip' 카테고리의 다른 글
자바 스크립트에서 대소 문자를 구분하지 않는 정규 표현식 (0) | 2020.08.05 |
---|---|
Google Apps Script를 디버깅하는 방법 (일명 Logger.log는 어디에 기록됩니까?) (0) | 2020.08.04 |
html 테이블에 대해서만 맨 위 행 고정 (고정 테이블 헤더 스크롤) (0) | 2020.08.04 |
StoryBoard ID는 무엇이며 어떻게 사용합니까? (0) | 2020.08.04 |
다중 서브 클래스에 단일 스토리 보드 uiviewcontroller를 사용하는 방법 (0) | 2020.08.04 |