java 初始化Number包装类型 博客分类: Java 初始化包装类型
程序员文章站
2024-02-23 19:06:46
...
java 初始化Number包装类型
比如有的java bean成员变量类型为Integer或者Long,
如果没有设置初始值,默认为null
下面的方法用来设置默认值
/*** * 数值类型(比如Integer,Long)如果值为null,则自动设置为0 * @param obj * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void convertNumberNull20(Object obj) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (obj == null) { return; } List<Field> fieldsList = getAllFieldList(obj.getClass()); if (ValueWidget.isNullOrEmpty(fieldsList)) { return; } for (int i = 0; i < fieldsList.size(); i++) { Field f = fieldsList.get(i); Object vObj = getObjectValue(obj, f); String typeName = f.getType().getName(); if (vObj == null) { if (typeName.equals("java.lang.Integer") || typeName.equals("java.lang.Short")) { f.set(obj, 0); } else if (typeName.equals("java.lang.String")) { f.set(obj, ""); } else if (typeName.equals("java.lang.Long")) { f.set(obj, 0L); } } } }
应用:
@Override protected void encode(ChannelHandlerContext ctx, ProxyMessage msg, ByteBuf out) throws Exception { int bodyLength = TYPE_SIZE + SERIAL_NUMBER_SIZE + inet_Port_SIZE + URI_LENGTH_SIZE; byte[] uriBytes = null; if (msg.getUri() != null) { uriBytes = msg.getUri().getBytes(SystemHWUtil.CHARSET_UTF); bodyLength += uriBytes.length; } if (msg.getData() != null) { bodyLength += msg.getData().length; } // write the total packet length but without length field's length. out.writeInt(bodyLength); ReflectHWUtils.convertNumberNull20(msg); out.writeByte(msg.getType()); out.writeLong(msg.getSerialNumber()); /*if(null==msg.getInetPort()){ msg.setInetPort(88888); }*/ out.writeInt(msg.getInetPort());//added by huangweii @2017-01-21 20:43:38 if (uriBytes != null) { out.writeByte((byte) uriBytes.length); out.writeBytes(uriBytes); } else { out.writeByte((byte) 0x00); } if (msg.getData() != null) { out.writeBytes(msg.getData()); } }
下一篇: c#获取光标在屏幕中位置的简单实例