gpt4 book ai didi

java - 泛型 Java 和类型参数的阴影

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:07:01 24 4
gpt4 key购买 nike

这段代码似乎工作正常

class Rule<T>
{

public <T>Rule(T t)
{

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

}
}
  1. 方法类型参数是否影响类类型参数?
  2. 另外,当您创建一个对象时,它是否使用类的类型参数?

例子

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 s 是不同的,但只有在使用 complete syntax 调用方法时才能看到它:

例如,这段代码是有效的:

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
}
}

我发现了另一个关于 calling methods with explicit generic types without something before them 的问题.看起来静态导入和同类方法调用是一样的。似乎 Java 不允许您以 <Type> 开始一行出于某种原因。

关于java - 泛型 Java 和类型参数的阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10151077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com