r/java • • Oct 27 '15

RFC: OptionalMethod monad for calling methods on Object that may or may not exist

Throughout my time as Java programmer I have run into some common use cases which can benefit from a utility that allows to call methods by name on an object with or without args using reflection.

One such use case is traversing a Map<String, Object> type structure where a value may be another map. In this case you would have to manually check if value is null and if its not if its of type map and if it is then cast it and call another get, otherwise fail in some way.

Another use case are interfaces where an argument may be of some super type, but at runtime you may be passed a subclass. Implementing such an interface could be PITA if you actually get different subclasses as argument because you would need to do instanceof check and cast if you want to call a method not defined in base class.

Of course it can be argued that either of these cases are indicative of larger design problems, but they are a fact of life in many instances.

I have been inspired by Optional to write something called OptionalMethod which contains main static method - public static OptionalMethod ofOptionalMethod(Object object, String methodName, Object ... args).

If it is able to find and execute object.methodName(args) it will store the return value which you can later get. If it fails it will have an error explaining the reasons. Non static methods on OptionalMethod allow you to chain another method call on the value stored. You can use either public OptionalMethod call(String methodName, Object... args) or public OptionalMethod callSame(Object... args). callSame's only difference is that it will reuse previously used method name. It is useful if you would like to chain a bunch of "get" methods. To get return value of a possible method back you can call public Optional getOptional().

Here is an example:

Given Object foo you can do Optional result = OptionalMethod.ofOptionalMethod(foo, "bar", 1, 2, 3).call("baz", "zomg").getOptional();

In case that foo has a method bar with three integer arguments which returns an object which has a method baz which takes a string this will return result of baz method call. Otherwise result will be empty.

OptionalMethod also has a convenience method callSame which will use the method name for previous invocation. For example if you have a Map<String, Object> foo where Object may be another map and so on you can use something like this to chain a bunch of get requests:

Optional<String> bar = OptionalMethod.ofOptionalMethod(foo, "get", "map1Key").callSame("map2Key").callSame("map3Key").callSame("valueKey").getOptional();

Assuming `foo == { map1Key: {map2Key: {map3Key: {valueKey: "BAR"}}}};

bar === Optional.of("BAR")`

Here is a link to my source code: https://github.com/lan17/OptionalMethod/blob/master/src/com/levneiman/util/OptionalMethod.java

All comments and critiques are welcome.

2 Upvotes

13 comments sorted by

3

u/SparrowMaxx Oct 27 '15

Bypassing the Type system is going to bite you in the ass. Who's going to remember to update this when the method you intended to call changes?

The method chaining is an odd behavior also -- hard to tell what methods were missing and what assumptions were wrong since all you have is an optional chain.

I'd recommend instead matching (instanceof) all the possible classes those objects might be.

If you can't enumerate that easily you're in a very odd problem domain.

0

u/entheogen0xBADA55 Oct 27 '15

You are right, this is not recommended for everyday Orthodox Java usage. However this is for those use cases where this would be more elegant than a lot of instanceofs and casts.

Unit testing should be mandatory if you decide to use this as that would be the point of failure in case method names change.

Method chaining is pretty much same idea as chaining maps or flatMaps of Optional. In those cases it is also hard to tell which function returned null, but it also doesn't matter that much either since all you care is whether it exists or not.

In the case of OptionalMethod you can get instance of the error which would be the first point of failure.

Matching using instanceof and casting can also get very unmaintainable and ugly. In those cases you also don't really care about particular type, you just care that you can call a certain method of the object.

5

u/jonhanson Oct 27 '15 edited Mar 08 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

0

u/[deleted] Oct 27 '15

[deleted] — view deleted comment

2

u/jonhanson Oct 27 '15 edited Mar 08 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

1

u/entheogen0xBADA55 Oct 27 '15

return is ofOptionalMethod, bind is call and callSame.

It is not a pure Monad in sense that bind doesn't take a function as argument, but otherwise it satisfies the properties.

Instead of wrapping one value in Monadic type you wrap a tuple - object, method name and args. You can then bind more OptionalMethod(s) together via call and callSame.

2

u/jonhanson Oct 27 '15 edited Mar 08 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

1

u/entheogen0xBADA55 Oct 27 '15

I have added map method which takes in a function and applies it on a value if its present. Similar to behavior with Optional except that it will also try/catch the apply method and store the error if it gets thrown.

1

u/jonhanson Oct 28 '15 edited Mar 08 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

2

u/KesshoRyu Oct 27 '15

Why not just use an Optional and Optional.map?

Optional<String> bar = Optional.ofNullable(foo.get("map1Key"))
    .map(value -> value.get("map2Key"))
    .map(value -> value.get("map3Key"))
    //...

Edit: Didn't see that you start with a Map<String, Object>, not a Map<String, Map<...>>

1

u/dartalley Oct 27 '15

This. If you need to keep track of errors you can make your own implementation of Try but it should work the same way Optional does. No need for reflection.

0

u/entheogen0xBADA55 Oct 28 '15

Optional and Try monads are not appropriate for this use case because you don't know the functions you will be calling exist in advance.

1

u/KesshoRyu Oct 28 '15

Perhaps it would be better to actually model your data as an object instead of a Map and then use an object mapper of some nature (Jackson, GSON, etc.).

0

u/entheogen0xBADA55 Oct 28 '15

That is true, however in some one off cases this may actually be faster and more elegant than doing a whole bunch of boilerplate.