在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?
当前回答
也许最令人惊讶的隐藏特性是sun.misc.Unsafe类。
http://www.docjar.com/html/api/ClassLib/Common/sun/misc/Unsafe.java.html
你可以;
Create an object without calling a constructor. Throw any exception even Exception without worrying about throws clauses on methods. (There are other way to do this I know) Get/set randomly accessed fields in an object without using reflection. allocate/free/copy/resize a block of memory which can be long (64-bit) in size. Obtain the location of fields in an object or static fields in a class. independently lock and unlock an object lock. (like synchronize without a block) define a class from provided byte codes. Rather than the classloader determining what the byte code should be. (You can do this with reflection as well)
BTW:不正确地使用这个类会杀死JVM。我不知道哪个jvm支持这个类,所以它不能移植。
其他回答
大多数人不知道他们可以克隆一个数组。
int[] arr = {1, 2, 3};
int[] arr2 = arr.clone();
不那么隐蔽,但很有趣。
你可以有一个没有main方法的"Hello, world"(它会抛出NoSuchMethodError思想)
最初由RusselW在最奇怪的语言功能上发布
public class WithoutMain {
static {
System.out.println("Look ma, no main!!");
System.exit(0);
}
}
$ java WithoutMain
Look ma, no main!!
同一个类的实例可以访问其他实例的私有成员:
class Thing {
private int x;
public int addThings(Thing t2) {
return this.x + t2.x; // Can access t2's private value!
}
}
还没有人提到instanceof的实现方式是不需要检查null的。
而不是:
if( null != aObject && aObject instanceof String )
{
...
}
只使用:
if( aObject instanceof String )
{
...
}
对于我面试的大多数Java开发人员来说,标记为块的职位是非常令人惊讶的。这里有一个例子:
// code goes here
getmeout:{
for (int i = 0; i < N; ++i) {
for (int j = i; j < N; ++j) {
for (int k = j; k < N; ++k) {
//do something here
break getmeout;
}
}
}
}
谁说goto在java中只是一个关键字?:)
推荐文章
- 在Selenium中等待页面加载
- Maven父pom vs模块pom
- 将JSON数据转换为Java对象
- Java的隐藏特性
- 使用Java 8的可选Stream::flatMap
- 使用管道字符("|")分割字符串
- 在IntelliJ中找不到Maven插件
- Java List.add() UnsupportedOperationException
- 连接两个字节数组的简单方法
- 为什么Mockito不模拟静态方法?
- Volatile boolean vs AtomicBoolean
- 在一个类中使用相同的方法实现两个接口。覆盖了哪个接口方法?
- 线程的上下文类装入器和普通类装入器之间的区别
- 如何在Java中正确地比较两个整数?
- 在Java中获取“unixtime”