在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?
当前回答
我差点忘了这个小宝贝。在任何正在运行的java进程上尝试这个:
jmap -histo:活动PID
您将得到给定VM中活动堆对象的直方图。作为一种快速计算某些类型的内存泄漏的宝贵方法。我使用的另一种技术是创建和使用所有集合类的有大小限制的子类。这将导致容易识别的失控集合出现快速故障。
其他回答
这是我的清单。
我最喜欢的(也是最可怕的)隐藏特性是,您可以从没有声明抛出任何东西的方法中抛出检查异常。
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中引入的可变参数。并且,与之前允许的数组声明更加一致。
没读到过
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来了解更多信息
因为还没有人说过(我认为)我最喜欢的功能是自动装箱!
public class Example
{
public static void main(String[] Args)
{
int a = 5;
Integer b = a; // Box!
System.out.println("A : " + a);
System.out.println("B : " + b);
}
}
java.util.Arrays中的asList方法允许变量参数、泛型方法和自动装箱的良好组合:
List<Integer> ints = Arrays.asList(1,2,3);
finally块中的控制权转移会丢弃任何异常。下面的代码不会抛出RuntimeException——它丢失了。
public static void doSomething() {
try {
//Normally you would have code that doesn't explicitly appear
//to throw exceptions so it would be harder to see the problem.
throw new RuntimeException();
} finally {
return;
}
}
从http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html
推荐文章
- 在流中使用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