|
1 | 1 | package org.cloudburstmc.nbt; |
2 | 2 |
|
| 3 | +import org.cloudburstmc.nbt.annotation.NBT; |
3 | 4 | import org.cloudburstmc.nbt.util.stream.LittleEndianDataInputStream; |
4 | 5 | import org.cloudburstmc.nbt.util.stream.LittleEndianDataOutputStream; |
5 | 6 | import org.cloudburstmc.nbt.util.stream.NetworkDataInputStream; |
6 | 7 | import org.cloudburstmc.nbt.util.stream.NetworkDataOutputStream; |
7 | 8 |
|
8 | 9 | import java.io.*; |
| 10 | +import java.lang.reflect.InvocationTargetException; |
| 11 | +import java.lang.reflect.Method; |
9 | 12 | import java.util.Arrays; |
10 | 13 | import java.util.StringJoiner; |
11 | 14 | import java.util.zip.GZIPInputStream; |
@@ -140,4 +143,30 @@ public static String printHexBinary(byte[] data) { |
140 | 143 | } |
141 | 144 | return r.toString(); |
142 | 145 | } |
| 146 | + |
| 147 | + /** |
| 148 | + * Write each {@link java.lang.reflect.RecordComponent RecordComponent} from record that be marked {@link NBT} to the specified nbtMap |
| 149 | + * |
| 150 | + * @param record the record |
| 151 | + * @param nbtMap the nbtmap |
| 152 | + * @return result NBT |
| 153 | + */ |
| 154 | + public static NbtMap putRecordToNBT(Record record, NbtMap nbtMap) { |
| 155 | + Class<? extends Record> clazz = record.getClass(); |
| 156 | + NBT annotation = clazz.getAnnotation(NBT.class); |
| 157 | + if (annotation == null) { |
| 158 | + throw new IllegalArgumentException("This record does not use @NBT annotation!"); |
| 159 | + } |
| 160 | + NbtMapBuilder builder = NbtMapBuilder.from(nbtMap); |
| 161 | + for (var c : clazz.getRecordComponents()) { |
| 162 | + String name = c.getName(); |
| 163 | + Method accessor = c.getAccessor(); |
| 164 | + try { |
| 165 | + builder.put(name, accessor.invoke(record)); |
| 166 | + } catch (IllegalAccessException | InvocationTargetException e) { |
| 167 | + throw new RuntimeException(e); |
| 168 | + } |
| 169 | + } |
| 170 | + return builder.build(); |
| 171 | + } |
143 | 172 | } |
0 commit comments