在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?
当前回答
JDK 1.6_07+包含一个名为VisualVM (bin/jvisualvm.exe)的应用程序,它是许多工具之上的一个漂亮的GUI。它似乎比JConsole更全面。
其他回答
局部类。 从包含类的外部实例化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
}
}
Javadoc——在正确编写的情况下(不幸的是,一些开发人员并不总是这样),它会为您提供一个清晰、连贯的描述,说明代码应该做什么,而不是它实际做什么。然后可以将其转换为一组不错的可浏览的HTML文档。如果你使用持续集成等方法,它可以定期生成,这样所有开发者都可以看到最新的更新。
当你不需要StringBuilder中包含的同步管理时,使用StringBuilder代替StringBuffer。它将提高应用程序的性能。
Java 7的改进甚至比任何隐藏的Java特性都要好:
菱形语法:Link
不要在实例化时使用那些infinite <>语法:
Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
// Can now be replaced with this:
Map<String, List<String>> anagrams = new HashMap<>();
switch中的字符串:Link
在switch中使用String,而不是old-C int:
String s = "something";
switch(s) {
case "quux":
processQuux(s);
// fall-through
case "foo":
case "bar":
processFooOrBar(s);
break;
case "baz":
processBaz(s);
// fall-through
default:
processDefault(s);
break;
}
自动资源管理Link
这段旧代码:
static void copy(String src, String dest) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dest);
try {
byte[] buf = new byte[8 * 1024];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
} finally {
out.close();
}
} finally {
in.close();
}
}
现在可以用更简单的代码代替:
static void copy(String src, String dest) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}
}
逗号和数组。字符串s[] = { “123”, “234”, };
推荐文章
- 在流中使用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