集册 Java实例教程 测试给定的对象是否为不可变的。

测试给定的对象是否为不可变的。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

545
测试给定的对象是否为不可变的。


import java.math.BigDecimal;/**来 自 时代Java**/

import java.math.BigInteger;

import java.util.*;

import java.util.function.Function;

import java.util.function.Predicate;


public class Main{

    public static void main(String[] argv) throws Exception{

        Object object = "nowjava.com";

        System.out.println(isImmutable(object));

    }

    private static final Set<Class> IMMUTABLE_CLASSES = Collections

            .unmodifiableSet(new HashSet<Class>(Arrays.asList(

                    Boolean.class, Byte.class, Short.class, Integer.class,/* from 时 代 J     a    v  a - nowjava.com*/

                    Long.class, Float.class, Double.class, Class.class,

                    BigInteger.class, BigDecimal.class, Currency.class)));

    /**


    /**

     * Tests if the given object is Immutable.  An object is considered Immutable either: <ol>

     * <li>One of the following

     * classes in the Standard Java Library: .</li>

     * <li>Marked with the org.paritybits.pantheon.common.Immutable<li> annotation.

     * @param object The object under test.

     * @return True if immutable

     * @throws NullPointerException If object is null.

     */

    public static boolean isImmutable(final Object object) {

        Class objClass = object.getClass();

        return IMMUTABLE_CLASSES.contains(objClass)

                || objClass.isAnnotationPresent(Immutable.class)

                || objClass.isAnnotationPresent(Idempotent.class);

    }

    /**

     * Allows a contains test to be made for any type of Iterable object.  If the iterable object

     * is a collection the contains method will be used, otherwise a naive iteration over

     * all the items will be used.

     *

     * @param iterable The iterable object that could contain the element

     * @param o element whose presence in this collection is to be tested.

     * @param <T> The type of object being used.

     * @return True if item was returned by the iterator.

     * @throws NullPointerException if iterable or item are null.

     */

    public 
展开阅读全文