加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

具有(im)可变属性的Groovy @Immutable类

发布时间:2020-12-14 16:26:14 所属栏目:大数据 来源:网络整理
导读:我正在尝试使用Groovy @ groovy.transform.Immutable来实现具有不受支持的“不可变”类型属性的类.在我的例子中,它是 java.io.File 例如,有类似的 @groovy.transform.Immutable class TwoFiles { File file1,file2} 给我以下编译错误 Groovyc: @Immutable pr
我正在尝试使用Groovy @ groovy.transform.Immutable来实现具有不受支持的“不可变”类型属性的类.在我的例子中,它是 java.io.File

例如,有类似的

@groovy.transform.Immutable class TwoFiles {
    File file1,file2
}

给我以下编译错误

Groovyc: @Immutable processor doesn’t know how to handle field ‘file1’ of type ‘java.io.File’ while compiling class TwoFiles.
@Immutable classes only support properties with effectively immutable types including:
– Strings,primitive types,wrapper types,BigInteger and BigDecimal,enums
– other @Immutable classes and known immutables (java.awt.Color,java.net.URI)
– Cloneable classes,collections,maps and arrays,and other classes with special handling (java.util.Date)
Other restrictions apply,please see the groovydoc for @Immutable for further details

一个选项我发现它扩展java.io.File使其成为Cloneable但我对这个解决方案不满意.下面的代码编译和工作,但拥有自己的java.io.File子类不是我想要的.

@groovy.transform.Immutable class TwoCloneableFiles {
    FileCloneable file1,file2

    class FileCloneable extends File implements Cloneable{

        FileCloneable(String s) {
            super(s)
        }

        // ... and other constructors ...
    }
}

所以我的问题是:有没有其他选项如何直接在这样的类中使用java.io.File?

为了@ groovy.transform.Immutable的目的,可能将java.io.File标记为“已知的不可变”(与java.awt.Color,java.net.URI似乎相同)?

解决方法

您是否尝试使用 knownImmutableClasses指定文件?这样的事情应该有效:

@groovy.transform.Immutable(knownImmutableClasses = [File])
class TwoFiles {
    File file1,file2
}

(使用File,您可能还可以通过以下方式获得所需的效果:

@groovy.transform.Immutable
class TwoFiles {
    String file1,file2
    public File getFile1() {return new File(file1)}        
    public File getFile2() {return new File(file2)}        
}

def f = new TwoFiles("/","/Users")
assert f.file1.class == File

)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读