首页 > 代码库 > NIO SelectionKey attachment()空指针错误

NIO SelectionKey attachment()空指针错误

Channel注册到Selector时添加了一个Object:

serverSocketChannel1.register(selector, SelectionKey.OP_ACCEPT, num[0]); 

后来取这个Object:

selectionKey.attachment();

出现空指针错误:

Exception in thread "main" java.lang.NullPointerException

很奇怪,后来发现第一次注册时添加了Object,后来注册时没有添加,导致了空指针错误:

client.register(selector, SelectionKey.OP_READ);

每次注册都添加Object,就不会有这个错误了:

client.register(selector, SelectionKey.OP_READ, num); 

NIO SelectionKey attachment()空指针错误