Refusal to use marker interface as parameter?

Heya all,
I've seen a lot of professional (ie Apache, Sun, etc) Java code that has code similar to this:
public void serialise(Object o)
   if (o instanceof Serializable)
      throw new IllegalArgumentException("Object is not serializable");
   ... code here...
}Whereas surely it could be re-written as:
public void serialise(Serializable o)
   ... code here...
}Thus giving us compile-time type safety. I seem to get the impression that 'Serializable' and 'Cloneable' and other such 'marker' interfaces shouldn't be used as parameters in this way because they are not 'real' interfaces as such. I usually prefer the second form; but I have seen both forms fairly commonly.
Any comments/suggestions on when it's better to use different ways?

Then allow me to be more specific, without retracting my original point. The following methods within java.io.ObjectInputStream and java.io.ObjectOutputStream which current exist as:
public Object readObject() throws IOException {}
public void writeObject(Object object) throws IOException {}Could easily be re-written (and be more specific and type-safe) via the following declarations:
public Serializable readObject() throws IOException{}
public void writeObject(final Serializable object) throws IOException {}I would further propose renaming then SerializableInputStream and SerializableOutputStream, as they do not truly take all instances of java.lang.Object.
- Saish

Similar Messages

  • What is the significance of Marker interface? Why are we using, even though

    What is the significance of Marker interface? Why are we using, even though it has no method?

    Well, what's the significance of an interface? They can define a set of methods a class may implement but the class could equally well implement these methods without the interface so why having interfaces at all?
    The answer is that the most important aspect of an interface is that it constitutes a type (you can declare variables of it). And it's a type regardless of how many methods it defines, including none. So the reason for having a marker interface is that you're interested solely in the type aspect of interfaces.

  • What is the use of Marker Interfaces?

    What is the use of marker interfaces?
    As it is not having any methods or fileds what is the benefit I will get by implementing those interfaces?
    Servlet implements SingleThread
    What it will do behind the scenes exactly as singleThread model is marker interface

    The use of marker interfaces is to act as markers (shock horror)
    It is quite a common way to tell a program what a class can/can't do: Cloneable, Serializable etc etc
    This doesn't change the functionality of the class itself, but is more an indication as to what can be done with this class.
    In this case the servlet container can then tell whether or not it implements the interface, and can treat it accordingly. Implementing this interface tells the container you want it to run this servlet in singleThreaded mode.
    Thats all there is to it.
    It would be along the lines of
    Servlet servlet = loadServlet("...")
    if (servlet instanceof SingleThreadModel){
    // Single threaded servlet - start new process for it
    else {
    // regular servlet - reuse existing object.

  • Use of marker Interface

    can any bdy plz tell me what is the use of marker interface ????

    Please search the forums before asking such a common question.

  • Marker interface use

    In which case Marker interface is getting use plz tell

    Marker Interfaces are giving specification to the JVM about the implementing classes.
    One of the features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes. Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose.
    Some examples of marker interfaces in the Java API include: -
    Java.lang.Cloneable
    A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
    java.io.Serializable
    Serialization is nothing but s saving the state of an object to persistent storage as byte stream. Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable. To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.
    java.util.EventListener
    A tagging interface that all event listener interfaces must extend.
    java.rmi.Remote
    The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are available remotely.
    Javax.servlet.SingleThreadModel
    Ensures that servlets handle only one request at a time. This interface has no methods. If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method.
    Java.util.RandomAccess
    This Marker interface used by List implementations (ArrayList, Vector) to indicate that they support fast (generally constant time) random access. The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.
    Javax.ejb.EnterpriseBean
    The EnterpriseBean interface must be implemented by every enterprise Bean class. It is a common superinterface for the SessionBean, EntityBean and MessageDrivenBean interfaces.
    Reference From Sun Documentation

  • Unusual use of interface defining static factory class with getInstance

    This question is prompted by a recent New to Java forum question ask about the differences between Interfaces and Abstract classes. Of course one of the standard things mentioned is that interfaces cannot actually implement a method.
    One of my past clients, one of the 500 group, uses interfaces as class factories. The interface defines a pubic static class with a public static method, getInstance, that is called to generate instances of a class that implements the interface.
    This architecture was very object-oriented, made good use of polymorphism and worked very well. But I haven't seen this architecture used anywhere else and it seemed a little convoluted.
    Here is a 'pseudo' version of the basic interface template and use
    -- interface that defines public static factory class and getInstance method
    public interface abc {
        public static class FactoryClass
            public static abc getInstance ()
                return (abc) FactoryGenerator(new abcImpl(), abc.class);
    -- call of interface factory to create an instance
    abc myABC = abc.Factory.getInstance();1. Each main functional area ('abc' in the above) has its own interface factory
    2. Each main functional area has its own implementation class for that interface
    3. There is one generator (FactoryGenerator) that uses the interface class ('abc.class') to determine which implementation class to instantiate and return. The generator class can be configured at startup to control the actual class to return for any given interface.
    I should mention that the people that designed this entire architecture were not novices. They wrote some very sophisticated multi-threaded code that rarely had problems, was high performance and was easy to extend to add new functionality (interfaces and implementing classes) - pretty much plug-n-play with few, if any, side-effects that affected existing modules.
    Is this a best-practices method of designing factory classes and methods? Please provide any comments about the use of an architecture like this.

    Thanks for the feedback.
    >
    I don't see how 'the generator class can be configured at startup to control the actual class to return for any given interface' can possibly be true given this pseudo-code.
    >
    I can see why that isn't clear just from what is posted.
    The way it was explained to me at the time is that the interface uses standard naming conventions and acts like a template to make it easy to clone for new modules: just change 'abc' to 'def' in three places and write a new 'defImpl' class that extends the interface and the new interface and class can just 'plug in' to the framework.
    The new 'defImpl' class established the baseline functionality that must be supported. This line
    return (abc) FactoryGenerator(new abcImpl(), abc.class);uses the initial version of the new class that was defined, 'abcImpl()', when calling the FactoryGenerator and it acted as a 'minimum version supported'. The generator class could use configuration information, if provided, to provide a newer class version that would extend this default class. Their reasoning was that this allowed the framework to use multiple versions of the class as needed when bugs got fixed or new functionality was introduced.
    So the initial objects would be an interface 'abc' and a class 'abcImpl'. Then the next version (bug fixes or enhancements) would be introduced by creating a new class, perhaps 'abcImpl_version2'. A configuration parameter could be passed giving 'abcImpl' as the base class to expect in the FactoryGenerator call and the generator would actually create an instance of 'abcImpl_version2' or any other class that extended 'abcImpl'.
    It certainly go the job done. You could use multiple versions of the class for different environments as you worked new functionality from DEV, TEST, QA and PRODUCTION environments without changing the basic framework.
    I've never seen any Java 'pattern' that looks like that or any pattern where an interface contained a class. It seemed really convoluted to me and seems like the 'versioning' aspect of it could have been accomplished in a more straightforward manner.
    Thanks for the feedback. If you wouldn't mind expanding a bit on one comment you made then I will mark this ANSWERED and put it to rest.
    >
    I don't mind interfaces containing classes per se when necessary
    >
    I have never seen this except at this one site. Would you relate any info about where you have seen or used this or when it might be necessary?

  • Using an interface as a parm in a methods

    Greetings I have an interface class that has a bunch of get methods. Then in another class I call the interface as a parameters. But what information do I put in it as I use it? the gets?
    [code
    //interface class
    public interface FillData {
              public String getTrader();
              public String getAccount();
    //Reg class
    public boolean insertData(FillData data){
    return true
    //Where I set the methods
    setTrader((String)table.getValueAt(i,0));
    importit.setAccount((String)table.getValueAt(i,1));
    insertData (//what goes in here???){
    Any more information needed lemme know? Thanks for any help!

    I have an interface public interface FillData {
    public String getTrader();
    public String getAccount();
    }I have a class with the interface as a parameter of a method
    public boolean insertData(FillData data){
    //do stuff
    return true
    }When I call the method what do I put in the parameter part of the method when I implement it?
    insertData(//what information do I put in here?)I guess my question is how do you use an interface??? I read the tutorial about implementing it in a class and all but how about when u use it as a method?
    Message was edited by:
    h2opologirly69

  • No performance gain when using local interfaces

    Hello,
    I'm doing some tests to compare performances between remote ejb interfaces and local ejb interfaces.
    I have two stateless session beans EJB1 and EJB2, EJB1 calls a method on EJB2, this method receives one object as the only parameter and returns it immediately. The parameter is a big object (~700ko). My test consists simply of making 1000 calls from EJB1 to EJB2, one time with remote interfaces, one time with local interface. For both tests, the EJBs run in the same container, same VM.
    The results show absolutely no differences between the remote and the local interface !
    As I found these results a bit surprising, I changed the serialization method of my parameter object this way:
    private void writeObject(java.io.ObjectOutputStream out) throws IOException {
    System.out.println("writeObject(MyBigObject)");
    out.defaultWriteObject();
    just to check if my object is serialized when using remote interface. And the response is no.
    So question is: is there an "undocumented optimization" of the stub/skel generated by weblogic which make local calls when calling a remote method inside the same VM ?
    Some precisions:
    - I'am using weblogic 8.1sp2
    - When calling remotely my EJB2 from an external batch (running in a separate VM), I see the message "writeObject(MyBigObject)" so the serialization is done in this case.

    <Fr?d?ric Chopard> wrote in message news:[email protected]..
    So question is: is there an "undocumented optimization" of the stub/skel generated by weblogic which make local calls when callinga remote method inside the same VM ?
    >
    Some precisions:
    - I'am using weblogic 8.1sp2
    - When calling remotely my EJB2 from an external batch (running in a separate VM), I see the message "writeObject(MyBigObject)" sothe serialization is done in this case.
    WebLogic 5.x, 6.x and 7.x do call by reference for co-located EJBs by default. 8.1 has this behavior turned off by default. You may
    experience call-by-reference optimization in 8.1 only if it has been turned on explicitly in the deployment descriptor.
    Hope this helps.
    Regards,
    Slava Imeshev

  • Newbie question on using an Interface

    I am something of an advanced beginner, one of those guys who can write simple stuff and maintain code but always have a bunch of questions.
    I am able to use an interface in a simple example shown below:
    import java.util.*;
    import java.text.*;
    public class ClassTest
    public static void main(String args[])
    new ClassTest();
    ClassTest()
    IfcPrintClass dao=null;
    try{ dao = (IfcPrintClass)Class.forName("ThatPrintClass").newInstance();
    }catch (Exception e) {};
    System.out.println(dao.PrintTheClass());
    try{ dao = (IfcPrintClass)Class.forName("ThisPrintClass").newInstance();
    }catch (Exception e) {};
    System.out.println(dao.PrintTheClass());
    } //end ClassTest
    What I am wondering is how do I instantiate (hope that's the right terminology) a class via an interface when the class has parameters? The API and other examples, at least ones I've seen, don't spell this out.
    I have to maintain a piece of code (ie, I didn't write it) with a class defined below. We need to create an interface for this class to implement so we can re-use this and similarly named classes for other projects. For example, the below listed class is to handle our SQL I/O, but naturally the db handling will varying from project to project. I want to be able to dynamically load a class within my code and pass the class name and directory into the package via ARGS (again, hope I'm using terminology correctly). I am trying to figure out how to adapt my above example to the below class instantiation, but cannot figure out how to pass the parameter along with it. I do know how to create an interface. In the below example "errorModule" is another class that handles our error and information logging, but is abstract enough that it will not change project to project. The "insertLoader" method is a sample method that the DAOLoader class will do, as is "isConnected".
    dao = new DAOLoader(errorModule);
    if(dao == null || !dao.isConnected()) //connection failed
    // handle this error
    else
    dbAlreadyFailed = false;
    if(firstDatabaseConnection)
    dao.insertLoader();
    thanks in advance, and hope you can help.

    As requested, here is the code I posted using code tags,and I'll do this in the future:
    ClassTest.java:
    import java.util.*;
    import java.text.*;
    public class ClassTest
    public static void main(String args[])
    new ClassTest();
    ClassTest()
    IfcPrintClass dao=null;
    try{ dao = (IfcPrintClass)Class.forName("ThatPrintClass").newInstance();
    }catch (Exception e) {};
    System.out.println(dao.PrintTheClass());
    try{ dao = (IfcPrintClass)Class.forName("ThisPrintClass").newInstance();
    }catch (Exception e) {};
    System.out.println(dao.PrintTheClass());
    } //end ClassTestMy actual code:
    dao = new DAOLoader(errorModule);
    if(dao == null || !dao.isConnected()) //connection failed
    // handle this error
    else
    dbAlreadyFailed = false;
    if(firstDatabaseConnection)
    dao.insertLoader();
    }IfcPrintClass.java:
    public interface IfcPrintClass
    String PrintTheClass();
    }ThatPrintClass.java:
    public class ThatPrintClass implements IfcPrintClass
    public String PrintTheClass()
    return "That";
    }Then I have a class ThisPrintClass:
    public class ThisPrintClass implements IfcPrintClass
    public String PrintTheClass()
    return "This";
    }

  • How can I use USB interface in Labview?

    Hi.
    Does labview allow to USB interface?
    I have been seen allowing GPIB and RS232.
    I'm beginer at Labview and wanna use USB interface for my target system and pc.
    I wanna know how to labview interfaces from target system to pc.
    And if Labview doesn't provide USB interface module, how can I use USB?
    Is using a USB at Labview hard to beginer?
    Plz, answer to my quetion.
    sorry, my English is very poor.
    thx for reading my article.

    You can access devices connected to the USB port, but not in the same way as you would a GPIB or RS232 device. There are no USB drivers like there is VISA for GPIB or serial. Rather devices that plug into the USB appear to the systen as some sort of standard resource like a printer, disk drive or IO board. LabVIEW then interacts with these devices as it would any other device of the same type.Look at it this way, if you have a USB daq device you will access it through MAX the same as if it were a plugin card. Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Mobility group only works using management interface?

    Hello,  in order to stablish the control traffic between 2 WLC-5508, it's necessary to use the management interface??
    It's possible using a dynamic interface o service port ?
    I think it only works with management interface,  but I don't understand the meaning of this text in the Configuration Manual:
    "Mobility control packets can use any interface address as the source, based on routing table."
    Thank you,

    No... mobility communication is done only with the management interface.
    Thanks,
    Scott
    *****Help out other by using the rating system and marking answered questions as "Answered"*****

  • MARKER INTERFACE WHY?

    hello i madhav new to this forum , i have doubt on marker interface . as it doesnot have any body why we r using that one instead of skipping.Is there any concept behind is there.More about my doubt is Take Example Cloneable Interface it Doesn't Have any Method In it,Clone() method is from Object class,then what is the necessity of implementing the interface .Why it should not be like that.
    what is real technolgy behind MarkerInteface and Why we r going to be used in what situations it will needed.And Lastly is there any method related to Serailizable interface if not what it do .
    marker interface can also called as Tag interface what is tag mean here just saying combing derived classes . i didn't get that one and how it will be .
    if u could explain with example or real time project it would be better for me
    thanks in advance

    What is a "marker" interface?
    Marker Interface pattern
    c2.com - Marker Interface
    experts.about.com - Marker Interfaces
    The Purpose of the Marker Interface
    Maximize your Design ROI with Marker Interfaces and JavaDoc

  • Marker interface query?

    what is the use of marker interface ?
    serializable ,clonable ,Runnable interfaces are marker interfaces .
    when any of the classes implemets these interfaces that classes will get the properities of marker interfaces .
    But , what r those properties?
    what is happening in back ground when we implements these marker interfaces ?

    what is the use of marker interface ?Let me ask a quesiton to you first: what is the use of a forum search?
    serializable ,clonable ,Runnable interfaces are
    marker interfaces .Not Runnable.
    when any of the classes implemets these interfaces
    that classes will get the properities of marker
    interfaces .If you mean by "implementing" only that it'll be included in the implements declaration: you're wrong. You also make sure that your class complies with the restrictions/behaviour imposed.
    what is happening in back ground when we implements
    these marker interfaces ?Nothing.

  • Marker interfaces

    what is the use of marker interfaces when do not specify any methods?

    This is discussed about once every week or every other week on this site. I suggest that you search this site for those previous discussions. They will have all you need. Also, have a look at google and wikipedia:
    http://en.wikipedia.org/wiki/Marker_interface_pattern

  • About Marker Interfaces

    what is the use of marker interfaces and y do we need them

    Here's an example I'm using:
    I've got a program which displays lots of tables, it doesn't just display them, it prints them and it dumps them to Excell files.
    Many of these tables have a total row at the bottom which needs highlighting. I flag the TableModel with a marker interface of my own. Then the various ways that table data is handled, when passed the TableModel, know to use a modifled JTable, or to use special formating flags on the last row.

Maybe you are looking for