How do I identify immutable objects in Java

后端 未结 15 1404
小蘑菇
小蘑菇 2020-11-30 22:40

In my code, I am creating a collection of objects which will be accessed by various threads in a fashion that is only safe if the objects are immutable. When an attempt is m

15条回答
  •  醉话见心
    2020-11-30 22:56

    Try this:

    public static boolean isImmutable(Object object){
        if (object instanceof Number) { // Numbers are immutable
            if (object instanceof AtomicInteger) {
                // AtomicIntegers are mutable
            } else if (object instanceof AtomicLong) {
                // AtomLongs are mutable
            } else {
                return true;
            }
        } else if (object instanceof String) {  // Strings are immutable
            return true;
        } else if (object instanceof Character) {   // Characters are immutable
            return true;
        } else if (object instanceof Class) { // Classes are immutable
            return true;
        }
    
        Class objClass = object.getClass();
    
        // Class must be final
        if (!Modifier.isFinal(objClass.getModifiers())) {
                return false;
        }
    
        // Check all fields defined in the class for type and if they are final
        Field[] objFields = objClass.getDeclaredFields();
        for (int i = 0; i < objFields.length; i++) {
                if (!Modifier.isFinal(objFields[i].getModifiers())
                                || !isImmutable(objFields[i].getType())) {
                        return false;
                }
        }
    
        // Lets hope we didn't forget something
        return true;
    }
    

提交回复
热议问题