简体   繁体   中英

What is the Java equivalent of creating an anonymous object in C#?

In C#, you can do the following:

var objResult = new { success = result };

Is there a java equivalent for this?

Java does not have type inference provided to C# by the var keyword, so whilst you can create anonymous types they're not much good since you can't get at their attributes.

So you can create an instance of an anonymous class like so:

Object myobj = new Object() {
  public final boolean success = true;
}

But since myobj is an instance of Object you can't access success in your code, and as you have created an instance of an anonymous class there is by definition no way to explicitly refer to this class.

In C# var solves this by inferring the type but there is no way to do this in Java.

Normally anonymous classes are used to create implementations of interfaces and abstract classes and so are referenced using the interface or parent class as the type.

With Java 10 you can use anonymous classes:

boolean result = true;

var objResult = new Object() {
    boolean success = result;
};

System.out.println(objResult.success);

You can use them with streams:

var names = List.of("John", "Peter", "Olaf");

var namesAndLength = names.stream().map(n -> new Object() {
    String name = n;
    int length = n.length();
}).collect(toList());

https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

https://developer.oracle.com/java/jdk-10-local-variable-type-inference

You can definitely write the equivalent as

Object objResult = new Object() {
    boolean success = result;
}

What you've done in this case is create an inline anonymous subclass of Object , which contains a success field instantiated to the value of result (which I've assumed is a boolean here, but could be anything).

However, this isn't very useful - since Java is strongly typed, and you have no way to refer to the anonymous class you created, you won't be able to refer to the success variable anywhere. Anonymous subclasses are generally used to either implement single-method interfaces, or perhaps provide an override of a superclass method - both of these cases are more useful since other code can invoke the overridden behaviour via the method declared on the parent class/interface.

So an anonymous subclass of Object which might be useful could be something like the following:

Object objresult = new Object() {
    @Override public String toString() {
        return result.toString(); 
    }
}

This behaviour is now exposed as you can call objResult.toString() in order to get the stringified result out.

In practice it would be better to define an interface with a getResult() method instead, and then implement this with either a concrete or anonymous class.

You just have a harder time getting the information out again:

Object objResult = new Object(){ public final boolean success = result; };

To get the fields you have to use reflection:

objResult.getClass().getDeclaredField("success").getBoolean(objResult)

For different types of the field success you will need different getters for the value.

There is similar but not identical functionality in the form of anonymous classes. The difference being that they have to implement a particular named interface or extend a named class.

SomeInterface obj = new SomeInterface() {
    // implement the interface
}

So, to approximate your example:

interface Result
{
    bool getSuccess();
}

// ...

bool result = DoSomething();
Result objResult = new Result() {
    bool getSuccess() { return result; }
}

But there is not much gain for this example.

http://www.docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm

Java has no equivalent feature for implicitly defining types with implemented by returning values. I guess the closest equivalent code would be to define an interface of "get" methods together with a handmade implementation.

interface Result {
    boolean success();
}
Result objResult = new Result() {
    public boolean success() { return result; }
};

You are probably better off taking a more Java-like approach to the specific problem. C# anonymous objects and Java anonymous classes are similar in name, but not functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM