Is there a functionality in Java similar to C#'s anonymous types?

后端 未结 3 1865
星月不相逢
星月不相逢 2021-02-19 21:58

I was wondering if there exists a similar functionality in Java similar to C#\'s anonymous types:

var a = new {Count = 5, Message = \"A string.\"};

3条回答
  •  半阙折子戏
    2021-02-19 22:16

    Java has a feature called local classes, which are somewhat similar. They're useful for creating a class or implementing an interface that doesn't really need to be known about outside of a particular method. The scope of the local class is limited by the code block that defines it.

    public void doSomething() {
        class SomeLocalClass {
            public int count = 5;
            public String message = "A string.";
        }
    
        SomeLocalClass local = new SomeLocalClass();
        System.out.println(local.count);
        System.out.println(local.message);
    }
    

    Unlike anonymous types in C#, Java local classes and their fields have explicitly defined types, but I imagine they might have some overlapping use cases.

提交回复
热议问题