泛型Java和类型参数的阴影
发布时间:2020-12-15 00:58:52 所属栏目:Java 来源:网络整理
导读:这段代码似乎工作正常 class RuleT{ public TRule(T t) { } public T void Foo(T t) { } } 方法类型参数是否影响类类型参数? 另外,当您创建对象时,它是否使用类的类型参数? 例 RuleString r = new RuleString(); 这通常适用于类的类型参数,在它们不冲突的
这段代码似乎工作正常
class Rule<T> { public <T>Rule(T t) { } public <T> void Foo(T t) { } } >方法类型参数是否影响类类型参数? 例 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. 解决方法
你所有的Ts都不同,但只有你用
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>开始一行.由于某些原因. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |