Currying is great to spice up your code! But this is not about cooking.
Continue reading “Java 8 Currying”Author: Claude
Generic Array Creation
Arrays of generic types are often hard to create and handle. I’ll show you how to create an array of a class with a generic parameter.
Is a Constructor a Method?
Why a constructor is not a method.
No, it’s not. In reflection both extend Executable
, but Constructor
does not extend Method
. It is a common misconception that constructors are methods and often asked about at job interviews.
Why a Consumer is not a Function.
java.util.function.Consumer
does not extend java.util.function.Function
. But what if you want a set of both types? Why isn’t there a ConsumerFunction?
A ConsumerFunction is not defined in java.util.function
. You can easily do it yourself. But you will see that it’s not that simple. void
is a keyword in Java. There is a class Void
and (by reflection) you can even get an instance of Void
. But you have to use a return statement to get a Function
.
Is Java object-oriented?
This is often asked at interviews. I’ll explain when to answer “yes” and when to answer “no”.
Continue reading “Is Java object-oriented?”
Blogs about Programming suck!
They do! And so do most online tutorials. Buy a good book instead!
Continue reading “Blogs about Programming suck!”
Misnomer: @FunctionalInterface
So it’s functional, right? Then why isn’t it a function? I’ll try to explain.
Continue reading “Misnomer: @FunctionalInterface”
How to replace Object.finalize()
There are many articles and blog posts about this topic but rarely are they complete. I’ll cover finalizers, Finalizer Guardian idiom, Dispose Pattern, PhantomReference and Cleanable.
LockOnce
Run code only once!
Project hosted on github: https://github.com/claudemartin/LockOnce
It’s just one single utility class to make sure code is run only once. And then there’s another one for easy “Lazy Initialization”.
I once wrote this for Java 7 but now it needs Java 8. It makes much more sense to use this with Lambdas. It’s a bit like the lazy keyword of Scala.
// declaration of lazy field:
final Supplier<Foo> lazy = Lazy.of(() -> ...);
// Access to the data:
Foo foo = lazy.get();
You can also register a “destructor”. This solves the problem that such fields (they are usually static final
) are never GCd and finalizers are utterly useless. In the same way you can have resources (they just have to implement AutoClose
) closed on shutdown.
Java Cleanup
## WARNING:
There already is sun.misc.Cleaner
. And Java 9 should even have java.util.Cleaner
or something like that. I simply didn’t know. So it’s better to wait for Java 9 or use sun.misc.Cleaner
.
If you are still interested:
Project home:
http://claude-martin.ch/java-cleanup/
I have a blog post about Finalizers and PhantomReferences:
Object.finalize()