为什么下面的代码会编译?
IElement.getX(String) 方法返回 IElement 类型或其子类的实例。 Main 类中的代码调用 getX(String) 方法。编译器允许将返回值存储到 Integer 类型的变量中(这显然不在 IElement 的层次结构中)。
public interface IElement extends CharSequence {
<T extends IElement> T getX(String value);
}
public class Main {
public void example(IElement element) {
Integer x = element.getX("x");
}
}
返回类型是否应该仍然是 IElement 的实例 - 即使在类型删除之后?
getX(String)方法的字节码是:
public abstract <T extends IElement> T getX(java.lang.String);
flags: ACC_PUBLIC, ACC_ABSTRACT
Signature: #7 // <T::LIElement;>(Ljava/lang/String;)TT;
编辑:将 String 替换为 Integer。
最佳答案
这实际上是一个合法的类型推断*。
我们可以将其简化为以下示例 (Ideone):
interface Foo {
<F extends Foo> F bar();
public static void main(String[] args) {
Foo foo = null;
String baz = foo.bar();
}
}
允许编译器推断出(实际上是荒谬的)交集类型String & Foo因为Foo是一个接口(interface)。对于问题中的示例,Integer & IElement是推断出来的。
这很荒谬,因为转换是不可能的。我们不能自己做这样的 Actor :
// won't compile because Integer is final
Integer x = (Integer & IElement) element;
类型推断基本上适用于:
在算法结束时,每个变量解析为基于绑定(bind)集的交集类型,如果它们有效,则调用编译。
流程从 8.1.3 开始:
When inference begins, a bound set is typically generated from a list of type parameter declarations
P<sub>1</sub>, ..., P<sub>p</sub>and associated inference variablesα<sub>1</sub>, ..., α<sub>p</sub>. Such a bound set is constructed as follows. For each l (1 ≤ l ≤ p):
[…]
Otherwise, for each type
Tdelimited by&in a TypeBound, the boundα<sub>l</sub> <: T[P<sub>1</sub>:=α<sub>1</sub>, ..., P<sub>p</sub>:=α<sub>p</sub>]appears in the set […].
所以,这意味着首先编译器从 F <: Foo 的边界开始。 (这意味着 F 是 Foo 的子类型)。
移至 18.5.2 ,返回目标类型被考虑:
If the invocation is a poly expression, […] let
Rbe the return type ofm, letTbe the invocation's target type, and then:
[…]
Otherwise, the constraint formula
‹R θ → T›is reduced and incorporated with [the bound set].
约束公式‹R θ → T›减少到 R θ <: T 的另一个界限,所以我们有 F <: String .
稍后根据 18.4 解决这些问题:
[…] a candidate instantiation
T<sub>i</sub>is defined for eachα<sub>i</sub>:
- Otherwise, where
α<sub>i</sub>has proper upper boundsU<sub>1</sub>, ..., U<sub>k</sub>,T<sub>i</sub> = glb(U<sub>1</sub>, ..., U<sub>k</sub>).The bounds
α<sub>1</sub> = T<sub>1</sub>, ..., α<sub>n</sub> = T<sub>n</sub>are incorporated with the current bound set.
回想一下,我们的边界集是 F <: Foo, F <: String . glb(String, Foo)定义为 String & Foo .这显然是 glb 的合法类型,只需要:
It is a compile-time error if, for any two classes (not interfaces)
V<sub>i</sub>andV<sub>j</sub>,V<sub>i</sub>is not a subclass ofV<sub>j</sub>or vice versa.
最后:
If resolution succeeds with instantiations
T<sub>1</sub>, ..., T<sub>p</sub>for inference variablesα<sub>1</sub>, ..., α<sub>p</sub>, letθ'be the substitution[P<sub>1</sub>:=T<sub>1</sub>, ..., P<sub>p</sub>:=T<sub>p</sub>]. Then:
- If unchecked conversion was not necessary for the method to be applicable, then the invocation type of
mis obtained by applyingθ'to the type ofm.
因此使用 String & Foo 调用该方法作为 F 的类型.我们当然可以将其分配给 String ,因此不可能转换 Foo到 String .
String 的事实/Integer显然没有考虑最终类。
* 注意:类型 erasure 与问题完全无关。
此外,虽然它也可以在 Java 7 上编译,但我认为我们不必担心那里的规范是合理的。 Java 7 的类型推断本质上是 Java 8 的一个不太复杂的版本。它编译的原因类似。
作为附录,虽然很奇怪,但这可能永远不会导致尚未出现的问题。编写一个返回类型仅从返回目标推断的泛型方法很少有用,因为只有 null可以从这样的方法返回而无需强制转换。
例如,假设我们有一些 map 类比,它存储特定接口(interface)的子类型:
interface FooImplMap {
void put(String key, Foo value);
<F extends Foo> F get(String key);
}
class Bar implements Foo {}
class Biz implements Foo {}
出现如下错误已经完全有效:
FooImplMap m = ...;
m.put("b", new Bar());
Biz b = m.get("b"); // casting Bar to Biz
所以我们可以也做Integer i = m.get("b");不是 新 的错误可能性。如果我们像这样编写代码,那么一开始就可能不合理。
一般来说,类型参数应该仅在没有理由绑定(bind)它的情况下从目标类型推断出来,例如Collections.emptyList()和 Optional.empty() :
private static final Optional<?> EMPTY = new Optional<>();
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
这没问题,因为 Optional.empty()既不能生产也不能消费T .
关于java - 为什么这个带有绑定(bind)的泛型方法可以返回任何类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29670018/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的