本文介绍了静态内部类需要导入注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在做一些 jUnit 测试,想编写不同的类,这些类具有相似的功能,但小到可以在单个类中编写.无论设计的决定如何,它都会让我遇到编译器错误,我不确定我所看到的规则是什么.

So I was doing some jUnit testing and wanted to write distinct classes that had similar functionality but were small enough to write within a single class. Regardless of the decision for design it brought me to a compiler error I am not sure what the rules are for what I saw.

你可以想象它看起来像

package foo;

@RunWith(Suite.class)
@SuiteClasses({ TestClassOne.class, TestClassTwo.class })
public class TestSuite{

   @RunWith(SpringJUnit4ClassRunner.class)
   public static class TestClassOne{

   }

   @RunWith(SpringJUnit4ClassRunner.class)
   public static class TestClassTwo{

   }
}

现在,当编译器启动它时,它会说TestClassOne 无法解析为类型.有一个简单的方法可以解决这个问题.例如,它需要显式导入静态类.

Now when the compiler kicks it it will say TestClassOne cannot be resolved to a type. There is an easy way to resolve this. It would require an explict import of the static class for instance.

import foo.TestSuite.TestClassOne;
import foo.TestSuite.TestClassTwo;

我的问题是,谁能解释一下编译器规则或注释可能无法看到类静态内部类的原因.请记住,包私有类看起来很好,并且无需导入即可编译.

My question is, can anyone explain what compiler rules or reasons there may be for the annotations to not be able to see the class static inner class. Keep in mind a package private class is seen fine and compiles without an import.

推荐答案

这是一个有趣的方案.根据[1],名称TestClassOne"的范围是整个"类TestSuite".

This is an interesting one. According to [1], the scope of the name "TestClassOne" is "the entire body of" class "TestSuite".

注解是否在主体" TestSuite 中?显然不是.但这不是很公平.范围规则是在引入注解之前定义的.如果在类的范围内考虑类注释,我认为没有任何问题.反正他们很亲密.

Is the annotation in "the body of" TestSuite? Apparently not. But that's not very fair. The scope rule was defined before annotation was introduced. I don't see any problem if a class annotation is considered in the scope of the class. They are very intimate anyway.

另一个问题是为什么在注释中可以引用简单的名称TestSuite"?事实证明,规范涵盖了这一点.注解是一个修饰符,它是类型声明的一部分,顶级类型的范围是包中的所有类型声明".

Another question is how come simple name "TestSuite" can be referenced in the annotation? It turns out the spec covers this one. Annotation is a modifier, which is part of the type declaration, and "The scope of a top level type is all type declarations in the package".

然而,规范有可能是偶然的.规则是在引入注解之前定义的,之后保持不变.因此,虽然它在技术上涵盖了案例,但它可能是一个意外.这并不是要怀疑语言设计师的脑力——整个规范实在是太复杂了.

However it is possible that the spec got it right by accident. The rules were defined before annotation was introduced, and remain the same afterwards. So although it covers the case in technicality, it could be an accident. This is not to doubt the brain power of language designers - the whole spec is just too damn complex.

[1] http://java.sun.com/docs/书籍/jls/third_edition/html/names.html#6.3

这篇关于静态内部类需要导入注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 20:50
查看更多