Calling a Superclass’ Method

A user on #java asked how one might invoke a method of a superclass recently, and received some general answers that more or less were right, but weren’t technically correct.

Maldivia pointed out that you would use method handles, which is sort of the gist of the (incorrect) answers given. The attempt was made to invoke the method via getDeclaredMethod(), which does not work.

The way to do it is to use MethodHandles.lookup() to get, well, a MethodHandles.Lookup object, which provides a way to get methods in the context of a class.

First, you’d get a MethodType reference, that refers to the _return value_ of the method. Then, you’d use findSpecial() – as one likely possibility – to find a method by name in a given class.

With that, you’d be able to invoke() the method.

Here’s code showing a superclass – Drink – and a main() in a subclass, Coffee, that has a bad call (the suggestion from the channel, tried and failing) and a good call, based on Maldivia’s suggestion, that actually does invoke Drink.toString() even when called from the context of a Coffee instance.

This is not expected to be held as an example of “what you should do” – for one thing, calling superclass’ methods outside of explicit access from a subclass is terrible design, in most cases, and for another, this is an example designed to run and not run properly or exhaustively. It’s simply a starting point.

import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

class Drink {
    public String toString() {
        return "This is a Drink!";
    }

}

public class Coffee extends Drink {
    public String toString() {
        return "This is a Coffee!";
    }

    static void badCall(Coffee coffee) throws Throwable {
        var method = coffee
                .getClass()
                .getSuperclass()
                .getDeclaredMethod("toString", null);
        System.out.println(method);
        System.out.println(method.invoke(coffee, null));
        System.out.println(coffee);
    }

    static void goodCall(Coffee coffee) throws Throwable {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodType type = MethodType.methodType(String.class);
        var m = lookup.findSpecial(coffee
                        .getClass()
                        .getSuperclass(),
                "toString",
                type,
                coffee.getClass()
        );
        System.out.println(m);
        System.out.println(m.invoke(coffee));
    }

    public static void main(String[] args) throws Throwable {
        Coffee coffee = new Coffee();
        badCall(coffee);
        goodCall(coffee);
    }
}

Java Multiline Properties

A channel member asked if there was a way to do multiline properties in Java, and if so, how was leading whitespace handled?

The answers are, respectively, “yes,” and “pretty much as you’d hope it was.”

The multiline character for Java properties is, as one might expect from every other programming language’s usage, the \ character, and the Properties.load() method will trim all leading whitespace from the property value. Here’s a sample:

// This is Example.java
package example;

class Example {
  public static void main(String[] args) {
// sorry for the gross formatting here, page width! try(var in=Example
.class
.getResourceAsStream("/foo.properties")) { var properties=new Properties(); properties.load(in); System.out.println(properties.getProperty("foo")); } } }

And the properties file, foo.properties, which should be visible in the classpath at the root:

# this is /foo.properties
# note how "multiline" is indented more than the rest
foo = this \
  is \
  a \
    multiline \
  property

If this is run and the classpath is set properly, the output should be this is a multiline property. You can embed newlines with \n as desired as well, if you need those in the output.

Hibernate Ignores Entity Listeners

I switched a codebase from EclipseLink as JPA provider to Hibernate and found out that with Hibernate you can not use inheritance in event listener classes. The JPA specs do not go into much detail on this topic so JPA providers are bound to handle this different from one another.

I separated my entity listeners from my entities even though it is possible to add methods annotated with e.g. @PostPersist directly in the entity class. The entity listeners themselves were less than trivial but only slightly so: I created a generic base class for all entity listeners and specialized subclasses for each entity.

public class EntityListenerBase<T> {
	@PostPersist
	public void postPersisted(T object) {
		SomeEventBus.sendEvent(createPostPersistEvent(object));
	}
	
	protected abstract Event createPostPersistEvent(T object);
}

public class ThingEntityListener extends EntityListenerBase<Thing> {
	@Override
	protected Event createPostPersistEvent(Thing thing) {
		return new ThingAdded(thing);
	}
}

Adding the entity listeners to the entity is straight-forward: Just add the @EntityListeners annotation to the entity and point it to the listener.

@Entity
@EntityListeners(ThingEntityListener.class)
public class ThingEntity implements Thing {
	…
}

EclipseLink had no trouble at all using event listeners like these. The problems started after I switched the JPA provider to Hibernate: at some point I realized that apparently the app was not generating any events anymore in response to persistence events. It was like the entity listeners weren’t even there!

After a longer debugging session into how Hibernate manages its event listeners I discovered that my previous approach for the event listeners was no longer viable, for two reasons.

The first reason is that Hibernate insists on the annotated event methods being declared directly in the entity listener class. Methods inherited from super classes are not scanned for event annotations! This is different from the behaviour when methods in the entity class itself are annotated; in that case, super classes annotated with @MappedSuperclass would be used to locate event listener methods as well. However, this is not the case for entity listener classes.

Upon moving the postPersisted method down to the subclass I stumbled upon the second reason: for every event annotation Hibernate only allows a single method in the entity listener class to be annotated with it. Now, because the original postPersisted method has a generic parameter and the subclass has a fixed type parameter, the compiler creates two versions of the method, one with Object as the parameter type, and one with the actual type I want, Thing. One of the methods is marked as synthetic but both get the annotation, and Hibernate doesn’t like that. Not. One. Bit.

So, the solution is simple, even if it means a little bit of code duplication over all the entity listeners: just remove the type hierarchy from the event listeners.

public class ThingEntityListener {
	@PostPersist
	public void postPersist(Thing thing) {
		SomeEventBus.sendEvent(new ThingAdded(thing));
	}
}

One could argue that this is actually even better; less class hierarchy, and all relevant listener methods are right there in the class, increasing visibility and reducing complexity.

Help! My Java Locale is Wrong in JDK11!

We discovered this issue when a user from the Netherlands reported that, upon upgrading to Java 11, his application now reported that the week started on Sunday. This is incorrect for the Netherlands, but the real issue was the change of behavior.

With JDK11, Java now loads locales differently. https://www.oracle.com/technetwork/java/javase/documentation/java11locales-5069639.html#providers details the loading behavior for JDK11, and how it supersedes previous versions. Notably, CLDR, or classloaded entries, now go before COMPAT, or things included with the JDK. This can lead to incorrect behavior with complex classpaths.

To supersede this setting, the java.locale.providers system setting is used. It’s a comma-separated list of values, where the possible values are the providers in the blog post above. The default value is CLDR,COMPAT,HOST,JRE where JRE is also COMPAT. The value that I would have expected is COMPAT,HOST,CLDR, where it uses the built-in locales first (from JDK9!), then the host locales, then the classloader locales. Setting -Djava.locale.providers=COMPAT will cause the JDK11 locale loader to act like the JDK9 locale loader.

Interesting Links – 5 Oct 2016

  • In Accounts is Everything Meteor Does Right, Pete Corey points out that Meteor‘s Accounts package dictates how user authentication and authorization will work, period, and that this removal of choice actually makes it entirely usable. Having wrestled with Shiro and Crowd and Spring Security and JAAS, it’s a point that’s hard to argue with – and while users of Shiro, etc., will probably say that those packages work as well as Accounts does, I’d have to humbly disagree, even while acknowledging how nice it is to have things like Shiro and Crowd. It’d be nice to have something that was just as drop-in for Java was Accounts is for Meteor. (Meteor is, BTW, a reactive application framework for NodeJS.)
  • User jdlee posted Maslow’s hierarchy of dev needs from Twitter – One gets the impression that the developer’s needs weren’t being met when designing that graph.
  • Also from jdlee, who was apparently crawling Twitter: “In Ruby, everything is an object. In Clojure, everything is a list. In Javascript, everything is a terrible mistake.”
  • User adimit gave high praise to Growing Object-Oriented Software Guided by Tests, saying that “it’s really simple but helping me write a test-driven app right now” and (coming from a Haskell background) “I’ve always hated OOP, but now I see how to do it properly, and it can be fun.” Anything that helps code quality improve is awesome, if you ask me.
  • From DZone: The Rise and Fall of Scala describes the apparent slow demise of Scala. The author backs it up, and it’s not a bad article; Scala’s awesome (I love it) but the criticisms are quite valid. Two areas where the author sees Scala remaining strong: Big Data and custom DSLs, definitely two Scala strengths.

Tags on javachannel.org

Articles on javachannel.org are going to start using Odersky’s “Scala Levels” as tags for new content (with old content being rated as they get maintained over time, possibly).
The levels are in two groups: A1, A2, A3, and L1, L2, and L3. The “A” stands for “application;” the “L” stands for “library.” Put simply, the features that tend to be found in applications and libraries are different; an application can prefer concrete types, whereas a library tends not to (if able); the skills and knowledge for writing applications or libraries are different.
An A1 programmer is a beginner at Java; an L3 programmer is expected to really know the language and its features well.
The skills are grouped like: A1, A2/L1, A3/L2, L3. The idea being expressed here is that before you should design a library, you need to be moderately skilled at Java – a beginner shouldn’t bother worrying about expressing ideas in a library.
Odersky actually grouped concepts for Scala in each level (for which he’s gotten some scathing criticism from Tony Morris, for example); eventually, I’d like to have the same kind of groupings for Java, if only to establish a baseline (which is what Odersky was doing, and what Morris apparently missed, in his quest for overreaction. Tony’s a brilliant guy, but like so many other brilliant people in this field, he’s desperate to find points of contention, and then wring them dry. Astute readers might note that Tony’s critique has no way through which to offer commentary…)
So: What you’ll start seeing is tips on javachannel.org being grouped by these levels by tags; the higher the level, the more complex the content is.