java 历年版本特征(简化)
Java5的新特性
特性列表
- 泛型
- 枚举
- 装箱拆箱
- 变长参数
- 注解
- foreach循环
- 静态导入
- 格式化
- 线程框架/数据结构
- Arrays工具类/StringBuilder/instrument
1、泛型
- 通配符类型:避免unchecked警告,问号表示任何类型都可以接受
- 限制类型
2、枚举
- EnumMap
- switch枚举
3、Autoboxing与Unboxing
4、vararg(动态参数)
5、annotation
- Inherited表示该注解是否对类的子类继承的方法等起作用
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface InProgress { }
- 指定Target
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,
ElementType.METHOD,
ElementType.CONSTRUCTOR,
ElementType.ANNOTATION_TYPE})
public @interface TODO {
String value();
}
- Target类型
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE
}
- rentation表示annotation是否保留在编译过的class文件中还是在运行时可读。
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
6、for/in
7、静态import
import static java.lang.System.err;
import static java.lang.System.out;
import java.io.IOException;
import java.io.PrintStream;
public class StaticImporter {
public static void writeError(PrintStream err, String msg)
throws IOException {
// Note that err in the parameter list overshadows the imported err
err.println(msg);
}
public static void main(String[] args) {
if (args.length < 2) {
err.println("Incorrect usage: java com.oreilly.tiger.ch08 [arg1] [arg2]");
return;
}
out.println("Good morning, " + args[0]);
out.println("Have a " + args[1] + " day!");
try {
writeError(System.out, "Error occurred.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
8、格式化
/**
* java.text.DateFormat
* java.text.SimpleDateFormat
* java.text.MessageFormat
* java.text.NumberFormat
* java.text.ChoiceFormat
* java.text.DecimalFormat
*/
9、threading
- uncaught exception
- blocking queue(阻塞队列)
- 线程池
- 每次提交任务时,如果线程数还没达到coreSize就创建新线程并绑定该任务。 所以第coreSize次提交任务后线程总数必达到coreSize,不会重用之前的空闲线程。
- 线程数达到coreSize后,新增的任务就放到工作队列里,而线程池里的线程则努力的使用take()从工作队列里拉活来干。
- 如果队列是个有界队列,又如果线程池里的线程不能及时将任务取走,工作队列可能会满掉,插入任务就会失败,此时线程池就会紧急的再创建新的临时线程来补救。
- 临时线程使用poll(keepAliveTime,timeUnit)来从工作队列拉活,如果时候到了仍然两手空空没拉到活,表明它太闲了,就会被解雇掉。
- 如果core线程数+临时线程数 >maxSize,则不能再创建新的临时线程了,转头执行RejectExecutionHanlder。默认的AbortPolicy抛RejectedExecutionException异常,其他选择包括静默放弃当前任务(Discard),放弃工作队列里最老的任务(DisacardOldest),或由主线程来直接执行(CallerRuns),或你自己发挥想象力写的一个。
10、其他
- Arrays
Arrays.sort(myArray);
Arrays.toString(myArray)
Arrays.binarySearch(myArray, 98)
Arrays.deepToString(ticTacToe)
Arrays.deepEquals(ticTacToe, ticTacToe3)
- Queue
- Override返回类型
- 单线程StringBuilder
- java.lang.instrument
参考
Java6的新特性
特性列表
- JSR223脚本引擎
- JSR199--Java Compiler API
- JSR269--Pluggable Annotation Processing API
- 支持JDBC4.0规范
- JAX-WS 2.0规范
1、JSR223脚本引擎
- 基本使用
public class BasicScripting {
public void greet() throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
//支持通过名称、文件扩展名、MIMEtype查找
ScriptEngine engine = manager.getEngineByName("JavaScript");
// engine = manager.getEngineByExtension("js");
// engine = manager.getEngineByMimeType("text/javascript");
if (engine == null) {
throw new RuntimeException("找不到JavaScript语言执行引擎。");
}
engine.eval("println('Hello!');");
}
public static void main(String[] args) {
try {
new BasicScripting().greet();
} catch (ScriptException ex) {
Logger.getLogger(BasicScripting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
- 绑定上下文
public class ScriptContextBindings extends JsScriptRunner {
public void scriptContextBindings() throws ScriptException {
ScriptEngine engine = getJavaScriptEngine();
ScriptContext context = engine.getContext();
Bindings bindings1 = engine.createBindings();
bindings1.put("name", "Alex");
context.setBindings(bindings1, ScriptContext.GLOBAL_SCOPE);
Bindings bindings2 = engine.createBindings();
bindings2.put("name", "Bob");
context.setBindings(bindings2, ScriptContext.ENGINE_SCOPE);
engine.eval("println(name);");
}
public void useScriptContextValues() throws ScriptException {
ScriptEngine engine = getJavaScriptEngine();
ScriptContext context = engine.getContext();
Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("name", "Alex");
engine.eval("println(name);");
}
public void attributeInBindings() throws ScriptException {
ScriptEngine engine = getJavaScriptEngine();
ScriptContext context = engine.getContext();
context.setAttribute("name", "Alex", ScriptContext.GLOBAL_SCOPE);
engine.eval("println(name);");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ScriptException {
ScriptContextBindings scb = new ScriptContextBindings();
scb.scriptContextBindings();
scb.useScriptContextValues();
scb.attributeInBindings();
}
}
2、JSR199--Java Compiler API
public class JavaCompilerAPICompiler {
public void compile(Path src, Path output) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(src.toFile());
Iterable<String> options = Arrays.asList("-d", output.toString());
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits);
boolean result = task.call();
}
}
}
3、JSR269--Pluggable Annotation Processing API
4、其他
- 支持JDBC4.0规范
- JAX-WS 2.0规范(包括JAXB 2.0)
- 轻量级HttpServer
Java7的新特性
特性列表
- suppress异常(新语法)
- 捕获多个异常(新语法)
- try-with-resources(新语法)
- JSR341-Expression Language Specification(新规范)
- JSR203-More New I/O APIs for the Java Platform(新规范)
- JSR292与InvokeDynamic
- 支持JDBC4.1规范
- Path接口、DirectoryStream、Files、WatchService
- jcmd
- fork/join framework
- Java Mission Control
1、suppress异常(新语法)
/**
* 记录异常,不被淹没
* addSuppressed
*/
class ReadFile {
public void read(String filename) throws BaseException {
FileInputStream input = null;
IOException readException = null;
try {
input = new FileInputStream(filename);
} catch (IOException ex) {
readException = ex;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
if (readException == null) {
readException = ex;
}else{
//使用java7的
readException.addSuppressed(ex);
}
}
}
if (readException != null) {
throw new BaseException(readException);
}
}
}
}
public void handle() {
ExceptionThrower thrower = new ExceptionThrower();
try {
thrower.manyExceptions();
} catch (ExceptionA | ExceptionB ab) {
System.out.println(ab.getClass());
} catch (ExceptionC c) {
}
}
3、try-with-resources(新语法)
实现AutoCloseable
/**
* @created 2014-07-21
*/
public class CustomResource implements AutoCloseable {
public void close() throws Exception {
System.out.println("进行资源释放。");
}
public void useCustomResource() throws Exception {
try (CustomResource resource = new CustomResource()) {
System.out.println("使用资源。");
}
}
public static void main(String[] args) {
try {
new CustomResource().useCustomResource();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
4、JSR341-Expression Language Specification(新规范)
public static void main(String[] args){
ELProcessor el = new ELProcessor();
assert (el.eval("Math.random()") instanceof Double);
}
5、JSR203-More New I/O APIs for the Java Platform(新规范)
- bytebuffer
- filechannel
6、JSR292与InvokeDynamic
- 方法句柄MethodHandle
public class ThreadPoolManager {
private final ScheduledExecutorService stpe = Executors
.newScheduledThreadPool(2);
private final BlockingQueue<WorkUnit<String>> lbq;
public ThreadPoolManager(BlockingQueue<WorkUnit<String>> lbq_) {
lbq = lbq_;
}
public ScheduledFuture<?> run(QueueReaderTask msgReader) {
msgReader.setQueue(lbq);
return stpe.scheduleAtFixedRate(msgReader, 10, 10, TimeUnit.MILLISECONDS);
}
private void cancel(final ScheduledFuture<?> hndl) {
stpe.schedule(new Runnable() {
public void run() {
hndl.cancel(true);
}
}, 10, TimeUnit.MILLISECONDS);
}
/**
* 使用传统的反射api
*/
public Method makeReflective() {
Method meth = null;
try {
Class<?>[] argTypes = new Class[]{ScheduledFuture.class};
meth = ThreadPoolManager.class.getDeclaredMethod("cancel", argTypes);
meth.setAccessible(true);
} catch (IllegalArgumentException | NoSuchMethodException
| SecurityException e) {
e.printStackTrace();
}
return meth;
}
/**
* 使用代理类
* @return
*/
public CancelProxy makeProxy() {
return new CancelProxy();
}
/**
* 使用Java7的新api,MethodHandle
* invoke virtual 动态绑定后调用 obj.xxx
* invoke special 静态绑定后调用 super.xxx
* @return
*/
public MethodHandle makeMh() {
MethodHandle mh;
MethodType desc = MethodType.methodType(void.class, ScheduledFuture.class);
try {
mh = MethodHandles.lookup().findVirtual(ThreadPoolManager.class,
"cancel", desc);
} catch (NoSuchMethodException | IllegalAccessException e) {
throw (AssertionError) new AssertionError().initCause(e);
}
return mh;
}
public static class CancelProxy {
private CancelProxy() {
}
public void invoke(ThreadPoolManager mae_, ScheduledFuture<?> hndl_) {
mae_.cancel(hndl_);
}
}
}
- 调用
public class ThreadPoolMain {
/**
* 如果被继承,还能在静态上下文寻找正确的class
*/
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private ThreadPoolManager manager;
public static void main(String[] args) {
ThreadPoolMain main = new ThreadPoolMain();
main.run();
}
private void cancelUsingReflection(ScheduledFuture<?> hndl) {
Method meth = manager.makeReflective();
try {
System.out.println("With Reflection");
meth.invoke(hndl);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
private void cancelUsingProxy(ScheduledFuture<?> hndl) {
CancelProxy proxy = manager.makeProxy();
System.out.println("With Proxy");
proxy.invoke(manager, hndl);
}
private void cancelUsingMH(ScheduledFuture<?> hndl) {
MethodHandle mh = manager.makeMh();
try {
System.out.println("With Method Handle");
mh.invokeExact(manager, hndl);
} catch (Throwable e) {
e.printStackTrace();
}
}
private void run() {
BlockingQueue<WorkUnit<String>> lbq = new LinkedBlockingQueue<>();
manager = new ThreadPoolManager(lbq);
final QueueReaderTask msgReader = new QueueReaderTask(100) {
@Override
public void doAction(String msg_) {
if (msg_ != null)
System.out.println("Msg recvd: " + msg_);
}
};
ScheduledFuture<?> hndl = manager.run(msgReader);
cancelUsingMH(hndl);
// cancelUsingProxy(hndl);
// cancelUsingReflection(hndl);
}
}
7、支持JDBC4.1规范
- abort方法
public class AbortConnection {
public void abortConnection() throws SQLException {
Connection connection = DriverManager
.getConnection("jdbc:derby://localhost/java7book");
ThreadPoolExecutor executor = new DebugExecutorService(2, 10, 60,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
connection.abort(executor);
executor.shutdown();
try {
executor.awaitTermination(5, TimeUnit.MINUTES);
System.out.println(executor.getCompletedTaskCount());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static class DebugExecutorService extends ThreadPoolExecutor {
public DebugExecutorService(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public void beforeExecute(Thread t, Runnable r) {
System.out.println("清理任务:" + r.getClass());
super.beforeExecute(t, r);
}
}
public static void main(String[] args) {
AbortConnection ca = new AbortConnection();
try {
ca.abortConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 自动关闭
public class SetSchema {
public void setSchema() throws SQLException {
try (Connection connection = DriverManager
.getConnection("jdbc:derby://localhost/java7book")) {
connection.setSchema("DEMO_SCHEMA");
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM author")) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}
}
public static void main(String[] args) {
SetSchema ss = new SetSchema();
try {
ss.setSchema();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 自动映射
public class UseSQLData {
public void useSQLData() throws SQLException {
try (Connection connection = DriverManager
.getConnection("jdbc:derby://localhost/java7book")) {
Map<String,Class<?>> typeMap = new HashMap<String,Class<?>>();
typeMap.put("java7book.Book", Book.class);
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM book")) {
while (rs.next()) {
System.out.println(rs.getObject(1, Book.class));
}
}
}
}
public static void main(String[] args) {
UseSQLData usd = new UseSQLData();
try {
usd.useSQLData();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
8、Path接口(重要接口更新)
public class PathUsage {
public void usePath() {
Path path1 = Paths.get("folder1", "sub1");
Path path2 = Paths.get("folder2", "sub2");
path1.resolve(path2); //folder1\sub1\folder2\sub2
path1.resolveSibling(path2); //folder1\folder2\sub2
path1.relativize(path2); //..\..\folder2\sub2
path1.subpath(0, 1); //folder1
path1.startsWith(path2); //false
path1.endsWith(path2); //false
Paths.get("folder1/./../folder2/my.text").normalize(); //folder2\my.text
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
PathUsage usage = new PathUsage();
usage.usePath();
}
}
9、DirectoryStream
public class ListFile {
public void listFiles() throws IOException {
Path path = Paths.get("");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, "*.*")) {
for (Path entry: stream) {
//使用entry
System.out.println(entry);
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
ListFile listFile = new ListFile();
listFile.listFiles();
}
}
10、Files
public class FilesUtils {
public void manipulateFiles() throws IOException {
Path newFile = Files.createFile(Paths.get("new.txt").toAbsolutePath());
List<String> content = new ArrayList<String>();
content.add("Hello");
content.add("World");
Files.write(newFile, content, Charset.forName("UTF-8"));
Files.size(newFile);
byte[] bytes = Files.readAllBytes(newFile);
ByteArrayOutputStream output = new ByteArrayOutputStream();
Files.copy(newFile, output);
Files.delete(newFile);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
FilesUtils fu = new FilesUtils();
fu.manipulateFiles();
}
}
11、WatchService
public class WatchAndCalculate {
public void calculate() throws IOException, InterruptedException {
WatchService service = FileSystems.getDefault().newWatchService();
Path path = Paths.get("").toAbsolutePath();
path.register(service, StandardWatchEventKinds.ENTRY_CREATE);
while (true) {
WatchKey key = service.take();
for (WatchEvent<?> event : key.pollEvents()) {
Path createdPath = (Path) event.context();
createdPath = path.resolve(createdPath);
long size = Files.size(createdPath);
System.out.println(createdPath + " ==> " + size);
}
key.reset();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Throwable {
WatchAndCalculate wc = new WatchAndCalculate();
wc.calculate();
}
}
12、jcmd utility
- jcmd -l
- jcmd pid help
- jcmd pid VM.flags查看启动参数
13、fork/join
14、Java Mission Control
15、其他
- Binary Literals支持
- Numeric Literals的下划线支持
- Strings in switch Statements
参考
- lamda表达式(重磅)
- 集合的stream操作
- 提升HashMaps的性能
- Date-Time Package
- java.lang and java.util Packages
- Concurrency
lamda表达式(重磅)
集合的stream操作
提升HashMaps的性能
Date-Time Package
java.lang and java.util Packages
- ConcurrentHashMap的stream支持
java 历年版本特征(简化)的更多相关文章
- 蓝桥杯java历年真题及答案整理1~20.md
蓝桥杯java历年真题及答案整理(闭关一个月,呕心沥血整理出来的) 1 算法是这样的,如果给定N个不同字符,将这N个字符全排列,最终的结果将会是N!种.如:给定 A.B.C三个不同的字符,则结果为:A ...
- Atitit.ati dwr的原理and设计 attilax 总结 java php 版本
Atitit.ati dwr的原理and设计 attilax 总结 java php 版本 1. dwr的优点相对于ajax来说..1 2. DWR工作原理1 3. Dwr的架构2 4. 自定义dwr ...
- java高版本下各种JNDI Bypass方法复现
目录 0 前言 1 Java高版本JNDI绕过的源代码分析 1.1 思路一的源码分析 1.2 思路二的源码分析 2 基于本地工厂类的利用方法 2.1 org.apache.naming.factory ...
- java的版本区别、下载、配置
参考:http://blog.csdn.net/liujun13579/article/details/7684604 java的版本区别 常用的 java 程序分为 Java SE.Java EE ...
- 解决linux下javac -version和java -version版本显示不一致
解决linux下javac -version和java -version版本显示不一致 [javascript] view plaincopy [root@localhost usr]# $JAVA_ ...
- JAVA的三大特征 封装继承多态- 简单总结
简单总结一下 封装-即从很多类的抽取相同的代码 写在一个类里. 好处是 代码的重用,安全. 继承-减少代码的书写. 其好处也是 代码的重用. 多态- 把不同的子类对象都当作父类来看,可以屏蔽不同子类对 ...
- asdm不能登录问题;浏览器必须是ie,不能是chrome或者firefox;java的版本,尤其是安全等级和例外需要调整
asdm不能登录问题:浏览器必须是ie,不能是chrome或者firefox;java的版本,尤其是安全等级和例外需要调整
- java-01 JAVA三大版本比较&JDK、JRE、JVM 的关系
1. java三大版本比较 1.1 java SE javaSE 是java标准版的简称,其定位是个人计算机应用(应用原生界面比较ugly) 全称:Java Platform Standard Edi ...
- Atitit..jdk java 各版本新特性 1.0 1.1 1.2 1.3 1.4 1.5(5.0) 1.6(6.0) 7.0 8.0 9.0 attilax 大总结
Atitit..jdk java 各版本新特性 1.0 1.1 1.2 1.3 1.4 1.5(5.0) 1.6(6.0) 7.0 8.0 9.0 attilax 大总结 1.1. Java的编年史2 ...
随机推荐
- 2019 计蒜之道 复赛 B. 个性化评测系统 (模拟,实现,暴搜)
24.02% 1000ms 262144K "因材施教"的教育方式自古有之,互联网时代,要实现真正意义上的个性化教育,离不开大数据技术的扶持.VIPKID 英语 2020 多万学员 ...
- JS深度比较两个对象是否相等
/** * 深度比较两个对象是否相等 * @type {{compare: compareObj.compare, isObject: (function(*=): boolean), isArray ...
- pam模块
main 循环监控 独立的程序 根据配置防护 登陆 ca cert 私有口令 openssl 证书口令??
- Linux学习-LVS跨网段DR模型和FWM多服务绑定
一.实验环境 系统:CentOS7.6 主机:5台 (虚拟机) 客户端1台:172.16.236.134/24 (NAT网卡),网关指向 172.16.236.185/24(路由服务器) 路由服务器1 ...
- echart-折线图,数据太多想变成鼠标拖动和滚动的效果?以及数据的默认圈圈如何自定义圆圈的样式
1.数据太多怎么办???想拖拽,想滑动 dataZoom: [ { type: 'slider', } ] dataZoom: [ { type: 'inside', }] 两种功能都需要,还想调样 ...
- 面试题常考&必考之--js数组排序冒泡排序和快速排序
冒泡排序: 原理:比较相邻的元素,将值大的元素交换到右边.(如果相等不进行交换) 实例: 要排列数组:[10,1,35,61,89,36,55] 第一趟排序: 第1次排序:10和1比较,10>1 ...
- webstorm注册码,亲测2016.1.1版
打开webstorm,点击帮助,注册 注册时,在打开的License Activation窗口中选择“License server”,在输入框输入下面的网址: http://idea.iteblog. ...
- moment使用,把某个时间时间戳转换成日期
1.某个时间时间戳转换成日期 moment(时间戳 ).format("YYYYMMDD") 2.获取某个日期当月的最后一天 moment(“2019-04-05”).endO ...
- uniapp开发
问题1:去掉导航条 给一个单独的页面隐藏顶部的 导航栏 可以在pages.json里 单独的路由style下面配置 "app-plus": {"titleNView&q ...
- url传输中+转为%2B取到变空格的问题
一个加密串,通过url传过来后怎么也解密不了. 原串: h1tQYMmnx7jdvowi9KnaEM5dHfamJ+rbaRnvhwhUmRAvyxpA2AGzszx5k9K0qdhiQUq7m42S ...