1

We know that we can create marker interface. Suppose I want to create a marker interface like Serializable interface.

How can I force the JVM to tell user to add serial version id as happens with the Serializable interface?

Can I use our own marker interface in file handling or in RMI calls instead of Serializable interface?

Suppose my marker interface is

public interface SyncBean {}

How can I make the JVM require adding serial version id for implementing classes?

h7r
  • 4,944
  • 2
  • 28
  • 31
Musaddique S
  • 1,539
  • 2
  • 15
  • 36
  • It basically comes down to: "How to do any custom compile time warnings in Java" and your best bet is compile time annotations. Check this out: http://stackoverflow.com/a/1754823/3020903 – Tarmo Mar 09 '16 at 07:55

1 Answers1

0

It's not pretty, but it seems like the compiler warning is specific to Serializable. As you can see here, there are not special annotations or anything on Serializable to make it act the way it does — the behavior is hard-coded into javac.

What you can do (still using an interface) is this:

public interface SyncBean {
    long getVersionID();
}

Implementation would look like this:

public class MySyncable {
    long getVersionID() { return 142L; }
}

You can make these static in Java 8.


Another (better) option is to use an annotation:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface SyncBean {
    public long versionID();
}

Implementation looks like this:

@SyncBean(142L)
public class MySyncable {
}

Access looks like this:

MySyncable.class.getAnnotation(SyncBean.class).versionID();