Unicode source code

One day I have read that java source code is considered as unicode text.

Today I want to try that :

$ echo "\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0063\u006C\u0061\u0073\u0073\u0020\u0041\u0020\u007B\u000A\u0020\u0020\u0020\u0020\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006F\u0069\u0064\u0020\u006D\u0061\u0069\u006E\u0028\u0053\u0074\u0072\u0069\u006E\u0067\u005B\u005D\u0020\u0061\u0072\u0067\u0076\u0029\u0020\u007B\u000A\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u006C\u006E\u0028\u0022\u0070\u006F\u0075\u0065\u0074\u0022\u0029\u003B\u000A\u0020\u0020\u0020\u0020\u007D\u000A\u007D" > A.java
$ javac A.java
$ java A
pouet

The unicode string is equivalents to the following code :

public class A {
    public static void main(String[] argv) {
        System.out.println("pouet");
    }
}
Advertisements

The perfect copy

The Prototype pattern allows to initialize a new instance with the state of an other.
It’s easy to implement this pattern when the fields of the instance are are of primitive types (int, …).
However, when the fields are references, It can be more complex to clone all the members recursively.

The JVM can help us do that more easily with serialization.

Thanks to ByteArrayStream you can write an object, and read the copy of the object.

You want to make the both classes cloneable :

class B {}
class A implements Cloneable {
    public B b = new B();

    @Override
    protected A clone() {
        try {
            return (A) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

We write two unit tests to check if the cloning is ok :

class CloneTest extends TestCase {
    private A a = new A();

   @Test
   public void testInstanceClone() {
       assertTrue(a != a.clone());
   }

   @Test
   public void testInstanceMembreClone() {
       assertTrue(a.b != a.clone().b);
   }
}

testInstanceClone passes but testInstanceMembreClone fails.

The clone seems good but the cloned references are the sames.

To create a perfect clone you can use the JVM and serializable objects as in this snippet :

class Cloner {
     static <T> T clone(T t) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(t);
            oos.flush();
            return (T) new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())).readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

You can now use it in the clone method :

    @Override
    protected A clone() {
        return Cloner.clone(this);
    }

Now the two tests pass :).

This tip is not the most performant way to clone an instance but it’s the most reliable.

Should I use the template method or the command pattern to create a hook ?

Sometimes you need to have a hook in your code. This hook allows other developers to make some of their code be executed within yours.

void m() {
    System.out.println("my code");
    // hook
    System.out.println("my code");
}

You have two ways to do that. The first way is the template method pattern and the second is the command pattern.
The template method uses inheritance while the command pattern use composition.

If you use the template method your code will be as follows :

abstract class A {
    void m() {
        System.out.println("my code");
        hook();
        System.out.println("my code");
    }
    void abstract hook();
}

class B extends A {
    void hook() {
        System.out.println("hook code");
    }
}

You can also write a stub implementation :

class A {
    void m() {
        System.out.println("my code");
        hook();
        System.out.println("my code");
    }
    void hook() {}
}

class B extends A {
    void hook() {
        System.out.println("hook code");
    }
}

But Inheritance is static, thus solved at compile-time. If you want a dynamically (run-time) modifiable hook, you have to use composition. You can do that thanks to the Command pattern.

class A {
    private Command command;
    public A(Command command) {this.command = command}
    void m() {
        System.out.println("my code");
        if (command != null) command.hook();
        System.out.println("my code");
    }
}

interface Command { void hook(); }
class StubCommand implements Command { public void hook() {} } // Empty hook
class CommandImpl implements Command {
    public void hook() { System.out.println("hook code"); }
}

There is no particular solution but generally the most reusable solution uses composition.

Implement State pattern with enum

State pattern allow to choose the correct action related to the state of an object. The goal is to get rid of if/elseif and switch blocks.

You can replace constants which represents state by implementing the pattern as follows :

public class A {
    private int state = State.OPEN;

    class State {
        public static final int OPEN = 1;
        public static final int CLOSE = 2;
    }
}
public class A {
    private State state;

    interface State {}
    class OpenedState implements State {}
    class CloseState implements State {}
}

But now if you want to compare the state, you must use the instanceof operator.

You can do better with enum :

public class A {
    private State state;
    public A(State state) { this.state = state; }
    public State getState() { return state; }
    public void setState(State state) { this.state = state; }

    public void doSomething() { state.doSomething(); }

    public static void main(String[] argv) {
        A a = new A(State.CLOSE);
        a.doSomething();
        a.setState(State.OPEN);
        a.doSomething();
    }
    
    enum State {
        OPEN(new StateOpen()), CLOSE(new StateClose());
    
        private StateInterface stateInterface;

        private State(StateInterface stateInterface) { this.stateInterface = stateInterface; }
        
        public void doSomething() { stateInterface.doSomething(); }
    
        public static interface StateInterface { void doSomething(); }
        public static class StateOpen implements StateInterface {
            public void doSomething() { System.out.println("open"); }
        }
        public static class StateClose implements StateInterface {
            public void doSomething() { System.out.println("close"); }
        }
    }
}

Automatic imports : are they inefficient ?

Both snippets have the same behaviour :

import java.util.ArrayList;
public class A {
    public static void main(String[] argv) {
        new ArrayList();
    }
}
import java.util.*; // automatic import
public class A {
    public static void main(String[] argv) {
        new ArrayList();
    }
}

But we can be curious about efficiency.
In fact the same bytecode will be produced :

[kaz@akina]$ cat A.jad
import java.util.ArrayList;
public class I {
    public static void main(String args[]) {
        new ArrayList();
    }
}

Automatic imports are processed at compile time, thus no difference exists at runtime.
However, compilation will be probably a bit slower.

How to customize dependency injection

Hi,

I often explain particular features of JSE but not JEE possibilities.
Today we’ll see how to make a custom injection with JEE.
This feature is not directly supported by JEE but with defaults interceptors it becomes possible.
The Steps are :
1/ Create the annotation which will be used to tag a member instance to inject.
2/ Write a default interceptor which acts at post construction. It must check if the annotation exists, and thanks to reflexion set the value.
3/ Use the annotation with your EJB.

Annotation definition :

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectedValue { }

Interceptor implementation :

public class CustomInterceptor {
    public void inject(InvocationContext invocation) throws IllegalAccessException {
        Object o = invocation.getTarget();
        for (Field field : o.getClass().getFields()) {
            if (field.isAnnotationPresent(InjectedValue.class)) {
                boolean previousAccessibility = field.isAccessible();
                field.setAccessible(true);
                try {
                    field.set(o, 42);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                field.setAccessible(previousAccessibility);
            }
        }
    }
}

Interceptor declaration :

<interceptors>
    <interceptor>
        <interceptor-class>ejb.CustomInterceptor</interceptor-class>
        <post-construct>
            <lifecycle-callback-method>
                inject
            </lifecycle-callback-method>
        </post-construct>
    </interceptor>
</interceptors>

Using of the interceptor :

@Stateless
public class MyEJBBean implements MyEJBRemote {
    @InjectedValue
    private int myValue;
}

Dependency injection is the foundation of IOC (Inversion of control) and with interceptors you can write your dependency injections.
Defaults interceptors are applied on all EJBs, but if you want, you can attach interceptor to a particular EJB.
With AOP (Aspect Oriented Programming), and thanks to pointcuts, you can precisely identify a method signature and act on it.
We’ll maybe see that later.

Final keyword is not used enough

Mostly when I see the final keyword, it is for defining a constant reference, whereas this is not the main use of “final”.

Remember that the final keyword is applied to references but not to objects. That means objects are mutable but we can’t reaffect an instance to the reference.
This behavior is the same if I use final on variables or parameters.

Now check this code :

void m(String p) {
    // Here my code
}

No problem, I’ve “p” parameter of type String and I can use it, but I can reaffect “p” :

void m(String p) {
    p = "new value";
    // Here my code
}

What’s the problem ? There is no problem, this code compiles and runs fine, but the question is why should I do that ?
Because reaffectation is like creating a new variable, I probably have other choices that reaffect the “p” reference.
This reaffectation can be difficult to see and It’s always a good idea to have immutable references when you can to avoid side effects.

We can talk about final members. If there is no reason to change a reference, make it final as in the following code :

public class C {
    private final List<String> data = new ArrayList<String>();

    public void m(final String p) {
        // Code here
    }
}

.