小编Jud*_*tal的帖子

从String.getBytes("UTF-8")处理UnsupportedEncodingException的推荐方法

在库方法中调用String.getBytes("UTF-8")时,处理UnsupportedEncodingException的推荐方法是什么?

如果我正确地阅读http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html,UTF-8编码应始终可用,这让我相信没有将此异常传递给库的使用者的原因(即,throws在方法签名中添加一个子句).似乎任何使UTF-8编码工具不可用的故障模式都是灾难性的,导致我编写这个处理程序:

    try
    {
        ....
        return "blah".getBytes("UTF-8");
    }
    catch (UnsupportedEncodingException e)
    {
        // we're assuming UTF-8 encoding is always available.
        // see
        // http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
        e.printStackTrace();
        return null; //prevent compile-time "method must return a result" errors
    }
Run Code Online (Sandbox Code Playgroud)

是否存在此代码段无法解决的故障模式?

java string character-encoding

17
推荐指数
1
解决办法
1万
查看次数

递归取消allOf CompletableFuture

如果我有

CompletableFuture<Something> future1 = service.request(param1);
CompletableFuture<Something> future2 = service.request(param2);
CompletableFuture<Void> many = CompletableFuture.allOf(future1, future2);
Run Code Online (Sandbox Code Playgroud)

我什么时候会发生什么many.cancel()?将future1future2一并取消?如果没有,最简单的方法是什么?我不愿意留住future1future2,只是为了能够取消他们时,我想取消many.

关于我为什么要这样做的一些背景:当接收一条数据时,我需要请求匹配的,可能未来的数据来执行计算.如果有更新的数据到达,我想取消先前计算的完成,因为结果将立即被新计算取代.

java java-8 completable-future

7
推荐指数
1
解决办法
1034
查看次数

在Java中,为什么运行时没有泛型类型信息?

考虑这个例子来自一本书,有一个超类Gen和一个子类Gen2 ...

class Gen<T> { }

class Gen2<T> extends Gen<T> { }
Run Code Online (Sandbox Code Playgroud)

现在这本书的状态将不会编译(让我们假设它在一个主方法中)

Gen2<Integer> obj = new Gen2<Integer>();

if (obj instanceof Gen2<Integer>) {

    //do something
}
Run Code Online (Sandbox Code Playgroud)

无法编译,因为运行时不存在泛型类型信息.如果它在运行时不存在,它何时存在?我认为它在编译时不会存在,但会在运行时存在.当然,以下适用于带有通配符的运行时...

if (obj instanceof Gen<?>) {

    //do something else

}
Run Code Online (Sandbox Code Playgroud)

所以要澄清一下,我的问题是为什么通用类型信息在运行时不存在?我忽略了一个简单的概念吗?

java generics

5
推荐指数
2
解决办法
3438
查看次数