泛型Java和类型参数的阴影

rub*_*buc 6 java generics

这段代码似乎工作正常

class Rule<T>
{

    public <T>Rule(T t)
    {

    }
    public <T> void Foo(T t)
    {

    }
 }
Run Code Online (Sandbox Code Playgroud)
  1. 方法类型参数是否影响类类型参数?
  2. 另外,当你创建一个对象时,它是否使用类的类型参数?

Rule<String> r = new Rule<String>();
Run Code Online (Sandbox Code Playgroud)

这通常适用于类的类型参数,在它们不冲突的情况下吗?我的意思是当只有类有一个类型参数,而不是构造函数,或者这是否在构造函数中查找类型参数?如果他们发生冲突,这会如何变化?

请参阅下面的讨论

如果我有一个函数调用

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.
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 7

T的所有内容都不同,但如果您使用完整语法调用方法,则只能看到它:

例如,此代码有效:

new <Float>Rule<Integer>().<Character>Foo();
Run Code Online (Sandbox Code Playgroud)

为了使这更容易解释,让我们假设您的代码是这样的:

class Rule<A>
{

    public <B>Rule()
    {

    }
    public <C> void Foo()
    {

    }
 }
Run Code Online (Sandbox Code Playgroud)

然后你可以显式声明泛型类型,如:

new <B>Rule<A>().<C>Foo();
Run Code Online (Sandbox Code Playgroud)

如果类型具有相同的名称,则将选择最内层的类型(T在方法上,而不是类):

使用此代码,参数:

class Rule<T>
{

    public <T>Rule(T t)
    {

    }
    public <T> void Foo(T t)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

那么这是有效的:

new <Float>Rule<Integer>(3.2f); 
Run Code Online (Sandbox Code Playgroud)

请注意,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
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现了另一个问题,它涉及使用显式泛型类型调用方法而没有它们之前的东西.看起来静态导入和同类方法调用是相同的.看起来Java不会<Type>因某些原因让你开始排队.