2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

您可以使用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
  }
}

其他回答

动态代理(在1.3中添加)允许您在运行时定义符合接口的新类型。它派上用场的次数多得惊人。

没读到过

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来了解更多信息

Self-bound泛型:

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

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

那么自JDK 1.5以来就存在的协变返回类型呢?它的宣传很差,因为它是一个不吸引人的附加,但据我所知,它对泛型工作是绝对必要的。

本质上,编译器现在允许子类将被覆盖方法的返回类型缩小为原始方法返回类型的子类。所以这是允许的:

class Souper {
    Collection<String> values() {
        ...
    }
}

class ThreadSafeSortedSub extends Souper {
    @Override
    ConcurrentSkipListSet<String> values() {
        ...
    }
}

您可以调用子类的values方法并获得一个排序的线程安全的字符串集,而不必向下强制转换为ConcurrentSkipListSet。

JDK发行版中的bin目录下的JVisualVM。监视甚至分析任何java应用程序,即使是没有使用任何特殊参数启动的应用程序。仅在Java 6SE JDK的最新版本中。