泛型Java和类型参数的隐藏
问题内容:
此代码似乎正常工作
class Rule<T>
{
public <T>Rule(T t)
{
}
public <T> void Foo(T t)
{
}
}
- 方法类型参数是否会遮盖类类型参数?
- 另外,在创建对象时,它是否使用类的type参数?
例
Rule<String> r = new Rule<String>();
在它们 不冲突 的情况下,这通常适用于类的类型参数 吗?
我的意思是,当只有类具有类型参数而不是构造函数时,还是在构造函数中查找类型参数?如果他们 确实发生冲突 ,这将如何改变?
请参阅下面的讨论
如果我有一个函数调用
x = <Type Parameter>method(); // this is a syntax error even inside the function or class ; I must place a this before it, why is this, and does everything still hold true. Why don't I need to prefix anything for the constructor call. Shouldn't Oracle fix this.
问题答案:
您所有T
的都不同,但是只有使用完整的语法调用方法时,您才能看到它:
例如,此代码有效:
new <Float>Rule<Integer>().<Character>Foo();
为了使这一点更易于解释,我们假设您的代码是这样的:
class Rule<A>
{
public <B>Rule()
{
}
public <C> void Foo()
{
}
}
然后,您可以显式声明通用类型,例如:
new <B>Rule<A>().<C>Foo();
如果类型具有相同的名称,则将选择最里面的一种(T
方法上的,而不是类):
使用此代码,获取参数:
class Rule<T>
{
public <T>Rule(T t)
{
}
public <T> void Foo(T t)
{
}
}
那么这是有效的:
new <Float>Rule<Integer>(3.2f);
请注意,T
在构造函数中Float
不是Integer
。
另一个例子:
class Example<T> {
public <T> void foo1() {
// T here is the <T> declared on foo1
}
public void foo2() {
// T here is the <T> declared on the class Example
}
}
我发现了另一个问题,该问题涉及使用显式泛型类型调用方法而在它们之前没有内容。似乎静态导入和相同类的方法调用是相同的。似乎Java <Type>
出于某种原因不允许您开始。