All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feilong.core.lang.ObjectUtil Maven / Gradle / Ivy

Go to download

feilong is a suite of core and expanded libraries that include utility classes, http, excel,cvs, io classes, and much much more.

There is a newer version: 4.0.8
Show newest version
/*
 * Copyright (C) 2008 feilong
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.feilong.core.lang;

import static com.feilong.core.Validator.isNotNullOrEmpty;

import com.feilong.core.Validate;

/**
 * {@link Object} 工具类.
 * 
 * 

判断相等

* *
*
    *
  1. {@link com.feilong.lib.lang3.ObjectUtils#equals(Object, Object)} 支持两个值都是null的情况
  2. *
  3. {@link java.util.Objects#equals(Object, Object)} (since jdk1.7) 也支持两个值都是null的情况
  4. *
*
* * @author feilong * @see com.feilong.lib.lang3.ObjectUtils * @see java.util.Objects * @since 1.0.0 */ public final class ObjectUtil{ /** Don't let anyone instantiate this class. */ private ObjectUtil(){ //AssertionError不是必须的. 但它可以避免不小心在类的内部调用构造器. 保证该类在任何情况下都不会被实例化. //see 《Effective Java》 2nd throw new AssertionError("No " + getClass().getName() + " instances for you!"); } //--------------------------------------------------------------- /** * 如果 object 是null或者empty,返回默认值 defaultValue. * *

示例:

* *
* *
     * ObjectUtil.defaultIfNullOrEmpty(null, null)      = null
     * ObjectUtil.defaultIfNullOrEmpty(null, "")        = ""
     * ObjectUtil.defaultIfNullOrEmpty(null, "zz")      = "zz"
     * ObjectUtil.defaultIfNullOrEmpty("abc", *)        = "abc"
     * ObjectUtil.defaultIfNullOrEmpty(Boolean.TRUE, *) = Boolean.TRUE
     * 
* *
* *

说明:

*
*
    *
  1. 使用该方法,可以简化你的代码
  2. *
  3. 如果使用 import static 的特性,代码会更加简洁
  4. *
  5. 如果你只需要判断 null的场景,你可以使用 {@link #defaultIfNull(Object, Object)}
  6. *
*
* * *

对下面的代码重构:

* *
* *
     * 
     * if (isNotNullOrEmpty(defaultReturnResult.getReturnObject())){
     *     return (String) defaultReturnResult.getReturnObject();
     * }else{
     *     return "redirect:/";
     * }
     * 
     * 
* * 可以重构成: * *
     * return ObjectUtil.defaultIfNullOrEmpty((String) defaultReturnResult.getReturnObject(), "redirect:/");
     * 
* *
* *

再比如:

* *
* *
     * 
     * private void putItemToMap(Map{@code >} map,String categoryName,Item item){
     *     List{@code } itemList = map.get(categoryName);
     * 
     *     if (isNullOrEmpty(itemList)){
     *         itemList = new ArrayList{@code <>}();
     *     }
     *     itemList.add(item);
     *     map.put(categoryName, itemList);
     * }
     * 
     * 
* * 可以重构成: * *
     * 
     * private void putItemToMap(Map{@code >} map,String categoryName,Item item){
     *     List{@code } itemList = ObjectUtil.defaultIfNullOrEmpty(map.get(categoryName), new ArrayList{@code }());
     *     itemList.add(item);
     *     map.put(categoryName, itemList);
     * }
     * 
* * 当然对于上面的case,你还可以直接调用 {@link com.feilong.core.util.MapUtil#putMultiValue(java.util.Map, Object, Object)} * *
* * @param * the type of the object * @param object * the {@code Object} to test, 可以是 {@code null} or empty * @param defaultValue * the default value to return, 可以是 {@code null} or empty * @return 如果 object 是null或者empty,返回 defaultValue,否则返回 object * @see #defaultIfNull(Object, Object) * @see "org.apache.commons.collections4.ListUtils#defaultIfNull(java.util.List, java.util.List)" * @since 1.7.2 */ public static T defaultIfNullOrEmpty(final T object,final T defaultValue){ return isNotNullOrEmpty(object) ? object : defaultValue; } /** * Returns a default value if the object passed is {@code null}. * *
     * ObjectUtil.defaultIfNull(null, null)      = null
     * ObjectUtil.defaultIfNull(null, "")        = ""
     * ObjectUtil.defaultIfNull(null, "zz")      = "zz"
     * ObjectUtil.defaultIfNull("abc", *)        = "abc"
     * ObjectUtil.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
     * 
* * @param * the type of the object * @param object * the {@code Object} to test, may be {@code null} * @param defaultValue * the default value to return, may be {@code null} * @return {@code object} if it is not {@code null}, defaultValue otherwise * @since 3.0.0 */ public static T defaultIfNull(final T object,final T defaultValue){ return object != null ? object : defaultValue; } //--------------------------------------------------------------- /** * 判断指定的对象 object是否是数组. * *

说明:

*
*
    *
  1. 支持判断原始类型数组 primitive 和包装类型数组
  2. *
*
* *

示例:

* *
* *
     * int[] i = {};
     * ObjectUtil.isArray(i);                       =true
     * 
     * ObjectUtil.isArray(new int[] { 1, 2, 3 });   =true
     * 
     * ObjectUtil.isArray(new Integer[0]);          =true
     * ObjectUtil.isArray(new String[0]);           =true
     * 
* *
* *

instanceof和 {@link java.lang.Class#isArray()}的区别:

* *
*

* 通常使用instanceof操作符去判断一个对象 object 是否是数组 array.
* 在JVM层次,instanceof操作符 translates to a specific "instanceof" byte code, which is highly optimized in most JVM * implementations.
*

* *

* 而反射的方法(getClass().isArray()) is compiled to two separate "invokevirtual" instructions.
* The more generic optimizations applied by the JVM to these may not be as fast as the hand-tuned optimizations inherent in the * "instanceof" instruction.
*

* *

* 有两种特殊情况: null references 和 primitive arrays.
*

* * * * * * * * * * * * * * * * * * * * * *
instanceofgetClass().isArray()
null referencefalseNullPointerException
原始类型数组primitive arrayfalsetrue
*
* * @param object * the object * @return 如果 object 是null,抛出 {@link NullPointerException}
* @see Java array reflection: isArray * vs. instanceof * @see How to see if * an object is an array without using reflection? * @since 1.3.0 */ public static boolean isArray(Object object){ Validate.notNull(object, "object can't be null!"); return object.getClass().isArray(); } //--------------------------------------------------------------- /** * 判断指定的对象 object 是否是原生类型数组. * *

示例:

* *
* *
     * 
     * ObjectUtil.isPrimitiveArray(1)                           = false
     * ObjectUtil.isPrimitiveArray(1L)                          = false
     * ObjectUtil.isPrimitiveArray("1")                         = false
     * 
     * 
     * ObjectUtil.isPrimitiveArray(new int[] {})                = true
     * ObjectUtil.isPrimitiveArray(new int[] { 1, 2 })          = true
     * ObjectUtil.isPrimitiveArray(new byte[] { 1, 2 })         = true
     * 
     * ObjectUtil.isPrimitiveArray(new String[] { "1", "2" })   = false
     * 
* *
* * @param object * the object * @return 如果 object 是null,抛出 {@link NullPointerException}
* @since 1.8.4 */ public static boolean isPrimitiveArray(Object object){ Validate.notNull(object, "object can't be null!"); return isArray(object) && object.getClass().getComponentType().isPrimitive();//原始型的 } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy