//-------------------------------------------------
// Litchi Game Server Framework
// Copyright(c) 2019 phantaci <phantacix@qq.com>
// MIT Licensed
//-------------------------------------------------
package litchi.core.jdbc.column;
import com.esotericsoftware.reflectasm.FieldAccess;
import com.google.protobuf.GeneratedMessageV3;
import litchi.core.jdbc.table.Table;
import litchi.core.jdbc.table.TableInfo;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* @author 0x737263
*/
public class ProtobufColumn extends AbstractColumnParser {
@Override
public void readColumn(Table<?> instance, TableInfo.TableColumnInfo columnInfo, ResultSet rs) throws SQLException {
FieldAccess fieldAccess = instance.getTableInfo().fieldAccess;
byte[] bytes = rs.getBytes(columnInfo.aliasName);
if (bytes == null) {
try {
Class<?> parseClass = columnInfo.getColumnType(0);
Method newBuilder = parseClass.getMethod("newBuilder");
bytes = ((GeneratedMessageV3.Builder<?>)newBuilder.invoke(null)).build().toByteArray();
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
Method parseFrom = null;
try {
Class<?> parseClass = columnInfo.getColumnType(0);
parseFrom = parseClass.getMethod("parseFrom", byte[].class);
fieldAccess.set(instance, columnInfo.fieldName, parseFrom.invoke(null, (Object) bytes));
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
@Override
public void writeColumn(ArrayList<Object> writeList, TableInfo.TableColumnInfo columnInfo, Object fieldValue) {
if (fieldValue == null) {
writeList.add(new byte[0]);
} else {
writeList.add(((GeneratedMessageV3) fieldValue).toByteArray());
}
}
}
(002)Java GoogleProtobuf 通过反射设置默认值
最新推荐文章于 2024-07-26 12:28:02 发布
这篇文章详细描述了LitchiGameServerFramework中的ProtobufColumn类,它扩展了AbstractColumnParser,用于处理数据库列数据,特别关注protobuf消息的读写操作,包括从ResultSet读取字节并解析,以及将protobuf对象转换为字节数组写入列表。
摘要由CSDN通过智能技术生成