在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?
当前回答
最终初始化可以推迟。
它确保即使使用复杂的逻辑流也始终设置返回值。很容易错过一个case并意外返回null。它并不是不可能返回null,只是很明显它是故意的:
public Object getElementAt(int index) {
final Object element;
if (index == 0) {
element = "Result 1";
} else if (index == 1) {
element = "Result 2";
} else {
element = "Result 3";
}
return element;
}
其他回答
它并不是完全隐藏的,但反射是非常有用和强大的。使用简单的class . forname("…"). newinstance()是很好的,其中类类型是可配置的。编写这种工厂实现很容易。
SwingWorker用于轻松管理后台线程的用户界面回调。
没读到过
Integer a = 1;
Integer b = 1;
Integer c = new Integer(1);
Integer d = new Integer(1);
Integer e = 128;
Integer f = 128;
assertTrue (a == b); // again: this is true!
assertFalse(e == f); // again: this is false!
assertFalse(c == d); // again: this is false!
通过搜索java的整数池(内部“缓存”从-128到127用于自动装箱)或查看integer . valueof来了解更多信息
这是我的清单。
我最喜欢的(也是最可怕的)隐藏特性是,您可以从没有声明抛出任何东西的方法中抛出检查异常。
import java.rmi.RemoteException;
class Thrower {
public static void spit(final Throwable exception) {
class EvilThrower<T extends Throwable> {
@SuppressWarnings("unchecked")
private void sneakyThrow(Throwable exception) throws T {
throw (T) exception;
}
}
new EvilThrower<RuntimeException>().sneakyThrow(exception);
}
}
public class ThrowerSample {
public static void main( String[] args ) {
Thrower.spit(new RemoteException("go unchecked!"));
}
}
此外,你可能想知道你可以抛出'null'…
public static void main(String[] args) {
throw null;
}
猜猜这打印了什么:
Long value = new Long(0);
System.out.println(value.equals(0));
猜猜这返回什么:
public int returnSomething() {
try {
throw new RuntimeException("foo!");
} finally {
return 0;
}
}
优秀的开发人员不应该对上述情况感到惊讶。
在Java中,你可以用以下几种有效的方式来声明数组:
String[] strings = new String[] { "foo", "bar" };
// the above is equivalent to the following:
String[] strings = { "foo", "bar" };
所以下面的Java代码是完全有效的:
public class Foo {
public void doSomething(String[] arg) {}
public void example() {
String[] strings = { "foo", "bar" };
doSomething(strings);
}
}
是否有任何有效的理由说明下面的代码不应该是有效的?
public class Foo {
public void doSomething(String[] arg) {}
public void example() {
doSomething({ "foo", "bar" });
}
}
我认为,上述语法可以有效地替代Java 5中引入的可变参数。并且,与之前允许的数组声明更加一致。
我个人很晚才发现java.lang.Void——结合泛型提高了代码的可读性,例如Callable<Void>
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap