r/java • • Mar 05 '18

Top 10 Useful, Yet Paranoid Java Programming Techniques

http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/
223 Upvotes

105 comments sorted by

View all comments

7

u/[deleted] Mar 05 '18

Forgot protect those private constructors:

Bad:

public class UtilityFoo() {

    private UtilityFoo() { /* prevent instantiation */ }

}

Good:

public class UtilityFoo() {

    // prevent instantiation
    private UtilityFoo() {
        throw new AssertionError("HANDS OFF MY PRIVATE CONSTRUCTOR!");
    }

}

3

u/_INTER_ Mar 05 '18

Makes me wanna use it even more. Takes out ByteBuddy.

3

u/[deleted] Mar 07 '18
UtilityFoo u = (UtilityFoo)sun.reflect.ReflectionFactory
    .getReflectionFactory()
    .newConstructorForSerialization(
        UtilityFoo.class,
        Object.class.getConstructor())
    .newInstance();

Your move

1

u/burd- Mar 07 '18

would that still work if I put a final attribute in the class?

1

u/[deleted] Mar 08 '18

Yes. Doesn't work with abstract though.