2024-04-20 09:00:01

Java的隐藏特性

在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?


当前回答

关闭钩子。这允许注册一个线程,该线程将立即创建,但仅在JVM结束时启动!因此,它是某种“全局jvm终结器”,您可以在这个线程中做一些有用的事情(例如关闭java资源,如嵌入式hsqldb服务器)。这适用于System.exit(),或CTRL-C / kill -15(当然,在unix上不适用kill -9)。

此外,它很容易设置。

            Runtime.getRuntime().addShutdownHook(new Thread() {
                  public void run() {
                      endApp();
                  }
            });;

其他回答

您可以使用Class<T>对象添加泛型类型的运行时检查,当在某个配置文件中创建类且无法为类的泛型类型添加编译时检查时,这非常方便。你不希望类在运行时爆炸,如果应用程序碰巧配置错误,你不希望所有的类都充满了检查的实例。

public interface SomeInterface {
  void doSomething(Object o);
}
public abstract class RuntimeCheckingTemplate<T> {
  private Class<T> clazz;
  protected RuntimeChecking(Class<T> clazz) {
    this.clazz = clazz;
  }

  public void doSomething(Object o) {
    if (clazz.isInstance(o)) {
      doSomethingWithGeneric(clazz.cast(o));
    } else {
      // log it, do something by default, throw an exception, etc.
    }
  }

  protected abstract void doSomethingWithGeneric(T t);
}

public class ClassThatWorksWithStrings extends RuntimeCheckingTemplate<String> {
  public ClassThatWorksWithStrings() {
     super(String.class);
  }

  protected abstract void doSomethingWithGeneric(T t) {
    // Do something with the generic and know that a runtime exception won't occur 
    // because of a wrong type
  }
}

Self-bound泛型:

class SelfBounded<T extends SelfBounded<T>> {
}

http://www.artima.com/weblogs/viewpost.jsp?thread=136394

javabean属性访问器方法不必以“get”和“set”开头。

甚至Josh Bloch在《Effective 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支持这个类,所以它不能移植。

作为初学者,我非常欣赏Java 6中的JConsole监控软件,它已经为我解决了一些问题,而且我还在不断地寻找它的新用途。

显然JConsole在Java 5中已经有了,但我认为现在它已经改进了,至少现在工作得更稳定了。

Java 5中的JConsole: Java 5中的JConsole

Java 6中的JConsole: Java 6中的JConsole

当你在做它的时候,好好看看本系列中的其他工具: java6故障排除工具