- 分别使用jdk,protobuf,json序列化反序列化一个特定类的对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\Person.txt"));
Person person = new Person();
oos.writeObject(person);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream("E:\\Person.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject();
System.out.println(o);
fis.close();
ois.close();
DataInfo.Student student = DataInfo.Student.newBuilder()
.setName("xxxx").setAge(100).setAddress("中国").build();
byte[] bytes = student.toByteArray();
DataInfo.Student student1 = DataInfo.Student.parseFrom(bytes);
String objectToJson = JSON.toJSONString(initUser());
System.out.println(objectToJson);
User user = JSON.parseObject(objectToJson, User.class);
System.out.println(user);
- 基于guava框架中事件总线@Listener注解实现具体事件的监听
@Service
public class EventListener {
@org.springframework.context.event.EventListener
public void onSynMsgEvent(CreateMsgEvent event){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Async
@org.springframework.context.event.EventListener
public void onAsynMsgEvent(CreateMsgEvent event){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- 应用启动时识别spring bean实例中标记有@Counter的方法
import java.lang.annotation.*;
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Counter{
boolean value() default true;
}
public class BeanFactory {
private static Map<String, Object> map = new HashMap<>();
static {
try {
Reflections edus = new Reflections("com.lagou.edu");
Set<Class<?>> clazzs = edus.getTypesAnnotatedWith(Counter.class);
for (Class<?> clazz : clazzs) {
Object object = clazz.getDeclaredConstructor().newInstance();
Counter service = clazz.getAnnotation(Counter.class);
if (StringUtils.isEmpty(service.value())) {
String[] names = clazz.getName().split("\\.");
map.put(names[names.length - 1], object);
} else {
map.put(service.value(), object);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}