+ @DoNotSerialize

This commit is contained in:
坏黑 2019-04-03 16:50:14 +08:00
parent 4bf37340bc
commit 3ad414df45
3 changed files with 32 additions and 5 deletions

View File

@ -0,0 +1,16 @@
package me.skymc.taboolib.common.serialize;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author sky
* @Since 2018-10-05 12:11
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DoNotSerialize {
}

View File

@ -29,6 +29,9 @@ public class TSerializer {
for (Map.Entry<String, JsonElement> jsonElementEntry : serializeObject.entrySet()) {
try {
Field declaredField = serializable.getClass().getDeclaredField(jsonElementEntry.getKey());
if (declaredField.isAnnotationPresent(DoNotSerialize.class)) {
continue;
}
declaredField.setAccessible(true);
Optional<TSerializerElementGeneral> serializer = Arrays.stream(TSerializerElementGeneral.values()).filter(serializerElements -> serializerElements.getSerializer().matches(declaredField.getType())).findFirst();
if (serializer.isPresent()) {
@ -56,13 +59,13 @@ public class TSerializer {
JsonObject serializeObject = new JsonObject();
for (Field declaredField : serializable.getClass().getDeclaredFields()) {
try {
if (!Modifier.isStatic(declaredField.getModifiers())) {
if (!declaredField.isAnnotationPresent(DoNotSerialize.class) && !Modifier.isStatic(declaredField.getModifiers())) {
declaredField.setAccessible(true);
Optional<TSerializerElementGeneral> serializer = Arrays.stream(TSerializerElementGeneral.values()).filter(serializerElements -> serializerElements.getSerializer().matches(declaredField.getType())).findFirst();
Object o = declaredField.get(serializable);
if (o == null) {
continue;
}
Optional<TSerializerElementGeneral> serializer = Arrays.stream(TSerializerElementGeneral.values()).filter(serializerElements -> serializerElements.getSerializer().matches(declaredField.getType())).findFirst();
if (serializer.isPresent()) {
serializeObject.addProperty(declaredField.getName(), serializer.get().getSerializer().write(o));
} else {

View File

@ -38,13 +38,20 @@ public class TSerializerExample {
* 基本类型不需要手动进行序列化
* 包含: StringintshortlongdoublefloatbooleanItemStackLocation
*/
private String text;
private int number;
private String text = "123";
private int number = 100;
/**
* 特殊类型需要进行手动序列化
* 本工具提供了基本容器的序列化方法
*/
private List<Double> list = Lists.newArrayList();
private List<Double> list = Lists.newArrayList(1.0, 2.0, 3.0);
/**
* 跳过序列化
*/
@DoNotSerialize
private String ignoreSerialize = "aaa";
/**
* 基本类型不会执行以下两个方法
@ -79,6 +86,7 @@ public class TSerializerExample {
"text='" + text + '\'' +
", number=" + number +
", list=" + list +
", ignoreSerialize='" + ignoreSerialize + '\'' +
'}';
}
}