Generics in Interfaces ?

Hi all,
Just a quick question about using generics in interfaces...is it possible to specify a type parameter for an abstract method, which is then made concrete in the implementing class ?
One example is the Comparable interface...it would be nice if, instead of using the "Object" type, you could specify that the parameter type for the method should be that of the implementing class. This would get rid of the compareTo(Object o) methods which can present a run-time problem.
Thanks,
Michael Dodsworth.

Hi again,
As part of a wider question...is it possible to specify the type parameter of a class/interface (as you would in a new statement) as part of an "extends/implements..." statement:
public class Foo
extends Hashtable<Integer, String>{
(the Hashtable example is from http://www-106.ibm.com/developerworks/java/library/j-djc02113.html)
All type parameters on Hashtable are then tied to Integer and String in the extending class; all inherited methods have the signatures of that particular incarnation of Hashtable.
Answering this, then answers the above question.
Thanks,
Michael Dodsworth.

Similar Messages

  • How to define generics in interfaces

    I want to define an interface for Person, which has 2 attributes, 'Owner' and 'Access', but these attributes may be different types for different implementations of the interface. I have another interface that takes Person, so I have something like this:
    public interface Person<O, A>
        public abstract O getOwner();
        public A getAccess();
    public interface Entry
        public void addPerson(Person<?, ?> person);
    }I then have a base Entry implementation that does
    import java.util.ArrayList;
    import java.util.List;
    public abstract class BaseEntry implements Entry
        protected List<Person<?,?>>  persons;
        public void addPerson(Person<?, ?> person)
            if (persons == null)
                persons = new ArrayList<Person<?,?>>();
            persons.add(person);
    }and finally I have a concrete class that wants to use Entry and Person interfaces to do somthing like
    public class RealEntry extends BaseEntry
        private int personCount;
        public void addPerson(Person<String, String> person)
            super.addPerson(person);
            personCount++;
    }and I might have another implementation that does
    public class ListEntry extends BaseEntry
        public void addPerson(Person<String, List<String>> person)
            super.addPerson(person);
    }but the concrete implementations do not compile in Eclipse with the message
    Name clash: The method addPerson(Person<String,String>) of type RealEntry has the same erasure as addPerson(Person<?,?>) of type BaseEntry but does not override it
    I've read the generics tutorial, but it's not helped me. I'm not absolutely certain I should be using wildcards as opposed to generic method.
    Anyone know what I'm doing wrong?
    Thanks
    Antony

    Hi Stefan, I see how your example breaks things, thanks.
    My 'Entry' is a simple queue class. I compiles OK if I add the O, A to Entry and implementations, i.e.
    public interface Entry<O, A>
        public void addPerson(Person<O, A> person);
    }but it seems strange (to me) that I have to define the O, A types for the Entry interface - it makes it cluttered. I thought it should be possible to have a generic Entry interface that takes a Person objects without having to tell Entry the subtypes of classes that make up the O and A inside Person.
    I could be trying to do something impossible, but I something think it has to be possible as it seems such a common type of usage, i.e. I can have many classes that all define different types of Person implementations and can store them in Entry implementations.

  • Tutorial for make a non-generic type class from a generic type interface

    Hi there,
    How can I make a non-generic type class from a generic type interface?
    I appreciate if somebody let me know which site can help me.
    Regards
    Maurice

    I have a generic interface with this signature
    public interface IELO<K extends IMetadataKey>
    and I have implemented a class from it
    public class CmsELOImpl<K extends IMetadataKey> implements IELO<K>, Cloneable, Serializable
    then I have to pass class of an instance CmsELOImpl to AbstractJcrDAO class constructor whit below signature
    public abstract class AbstractJcrDAO<T> implements JcrDAO<T> {
    public AbstractJcrDAO( Class<T> entityClass, Session session, Jcrom jcrom ) {
              this(entityClass, session, jcrom, new String[0]);
    So I have made another class extended from AbstractJcrDAO. Below shows the code of this class and itd constructor
    public class ELODaoImpl extends AbstractJcrDAO<CmsELOImpl<IMetadataKey>> {
         public ELODaoImpl( Session session, Jcrom jcrom ) {
         super(CmsELOImpl.class , session , jcrom, MIXIN_TYPES);
    and as you see in its constructor I am calling the AbstractJcrDAO constructor by supper method
    then I got this error on the line of super method
    The constructor AbstractJcrDAO(class<CmsELOImpl>, session, Jcrom, String[]) is undefined.
    as I know java generics are implemented using type erasure. This generics are only
    in the java source file and not in the class files. The generics are only used by the compiler and
    they are erased from the class files. This is done to make generics compatible with (old) non generics java code.
    As a result the class object of AbstractJcrDAO<CmsELOImpl<IMetadataKey>>
    is AbstractJcrDAO.class. The <CmsELOImpl<IMetadataKey>> information is
    not available in the class file. As far as I understand it, I am looking a way
    to pass <CmsELOImpl<IMetadataKey>>, if it is possible at all.
    Maurice

  • Generics in interfaces parameters

    My post is a feature request. If anyone have informations on forthcoming and related developments, please send me.
    I want to implement a graph class with nodes and edges collections and express in the implements section that this class supports such features (I don't take into account any delegation mechanism), graph can be considered as a String / Node map or as String / Edge one :
    public class Graph implements Map<String, Node>, Map<String, Edge> {
    but when compiling, I have interfaces method conflicts such as :
    "The return type is incompatible with Map<String,Edge>.get(Object), Map<String,Node>.get(Object)"
    because one get(Object) method is present in each interface. I would have rather liked to have a get(Node) and a get(Edge) methods. In other words, I would have liked to have Map<K,V>.get(K) method in Map interface.
    Does anyone know why Java Generics are not fully introduced in interfaces and maybe in some classes ? Is it a technical reason ? A workaround ? An intermediate development stage ?
    Thx.

    public class Graph implements Map<String, Node>, Map<String, Edge> {The problem is that after compilation, when the object code is produced, any "type parameter" information is erased (you need to read up on Java reflection more closely).
    Thus, there is only one Map class in the runtime (not one for every possible combination of type parameters). and any references to, say, Map<String,Node>.put() become, at runtime, just Map.put().
    So you can't do what you want, because at compile time, your two parent interfaces are "different", but at runtime, they would be the same. The message could be better, I agree.
    To do what you want:
    * If your two classes (Edge and Node) have no relationship to each other, then you'll have to implement Map<String,Object>.
    * If they do have a common ancestor, you can declare it as extending Map<String,CommonAncestor>.
    In both cases, you'll have to, e.g. downcast the result of get() to the right type.

  • Generic ADT / Interface to implementation

    Hello, I'm new to java, hope anyone can help.
    I have to implement a priority queue that should meet the following interface (note: please ignore the '>' after 'Comparable'):
    public interface PriorityQueue<E extends Comparable<E>> {
        boolean offer(E o);
        E poll();
        E peek();
        boolean isEmpty();
    }I'm having problems with the offer(E o) method... I wrote this:
    public class ListPriorityQueue<E extends Comparable<E>> implements PriorityQueue {
    public boolean offer(E o) { return false; }
    }I thought it would work, but Eclipse gives me the following error on that line:
    "Name clash: the method offer(E) of type ListPriorityQueue<E> has the same erasure has offer(E) of type PriorityQueue but does not override it"
    It also gives me this error at class level:
    "The type ListPriorityQueue<E> must implement the inherited abstract method PriorityQueue.offer(Comparable)"
    What should I do?

    "Name clash: the method offer(E) of type
    ListPriorityQueue<E> has the same erasure has
    offer(E) of type PriorityQueue but does not override
    it"
    implements PriorityQueue<E>>
    It also gives me this error at class level:
    "The type ListPriorityQueue<E> must implement
    the inherited abstract method
    PriorityQueue.offer(Comparable)"
    What should I do?You have to either implement all the methods declared in the interface, or declare your class as abstract.

  • Does NI offer a generic LabVIEW interface for the PCI-1424 frame grabber?

    I am attempting to grab frames from a DuncanTech camera using a PCI-1424. The vendor's software was developed in the LabVIEW, but I only have the executable and they seem unwilling to provide the source file(s) - essentially, the vendor software only displays the images (no capture capabilities). In the interests of time, I would like to locate/purchase a generic LabVIEW image acquisition front-end, if available.

    MJP;
    Your PCI-1424 card should include several examples. Check the directory where the software for the camera was installed (Usually "Program Files\National Instruments\NI-IMAQ")
    Also, if you have MAX (Measurement & Automation Explorer), you can access your card from there and snap images.
    Other than that, I think you have to write your own code or ask somebody to do it for you.
    Regards;
    Enrique
    www.vartortech.com

  • Generics and interface

    Ok let's say I have an Interface A
    I have a Class B whom extends A.
    In another class, I have private member :
    List<A> xyz;
    In a method, I receive (List<B> listabc);
    I want to have in xyz a reference to all listabc items, what is the best way to do it? Cast doesn't work, so I have to iterate on abc ?
    Thanks.

    Change xyz to List<? extends A>

  • Favorites - Generic User Interface Functions - SAP Library

    To add a comment, please log in or register on the top of this page and choose Reply. Please write your comment in English.
    You can also go back to the SAP help page.

    Hi,
    not sure why your download stops.. you can also try to download via this link: [http://www.sapdesignguild.org/resources/CRM-UI-Guidelines-Customers.pdf|http://www.sapdesignguild.org/resources/CRM-UI-Guidelines-Customers.pdf] (Document is 17,4MB of size)
    Here the guidelines also have been posted together with an article about the CRM 2007 Web Client UI.
    Hope this helps
    Best regards
    Ingo

  • Help inheriting multiple generic interfaces of same type

    Hi-
    I am trying to re-factor some current code bloat.
    Here is the solution I want
    I want to define one generic subscriber interface, e.g.
    public interface Subscriber <TYPE> {
    public void valueChanges (TYPE T) ;
    And then I would like to (in theory) implements a class like this
    public class MyClass extends foo implements Subscriber<String> ,
    Subscriber <Integer> , Subscriber <Double> {
    public void valueChanged (String s) {
    public void valueChanged (Integer s) {
    public void valueChanged (Double s) {
    But this does not seem to be allowed becuase it says you can not inherit the
    same interface multiple times. I even tried something like this
    public interface Stringsubscriber implements Subscriber <String> for all the
    interfaces to specialize. That does not work.
    Can this be done (via some mechanism) in java or is this not possible.
    I am just learning the way generics work (I come from c++ world were templates
    are a bit more flexible and work a bit differently so its trying).
    Any hlep would be great.
    thanks in advance
    matt

    OK, Bruce, I'll bite: how do you attach
    parameterized types as annotation member values?
    There's no ".class" for them. It must be textual,
    , right? No.
    Actually I don't attach them as such, I put them somewhere else where I can find them by association.
    And you parse these stringual declarations
    later?The mirror API does not have an equivalent method to com.sun..javadoc.ClassDoc.findClass(String name), so you can't do it textually unless you require every type to be fully qualified. Thats too ugly for me.
    I tried writing a recursive annotation like this@interface Type {
        Class<?> value();
        Type[] args() default {};
    }but you can't write cyclic annotations (whose members are of its own type, directly or indirectly).
    So I thought that since I was annotating a class, I would just create some placeholder interfacesinterface S2WFGC1<T1> {}
    interface S2WFGC2<T1,T2> {}
    thru
    interface S2WFGC15<T1,T2,... T15> {}and do this
        @MyAnnotation(base=Map.class, add=@Flavor(EventDispatcher.class))
    class MyClass implements S2WFGC2<
                    Map<String,Integer>,
                    EventDispatcher<FooListener,FooEvent>
                > {
    }which gets interpreted as
        @MyAnnotation(
            base=Map<String,Integer>,
            add=@Flavor(EventDispatcher<FooListener,FooEvent>)
    class MyClass {}So I just put the raw type in the annotation, and for each of those (because the annotation is more complex than above), I get the type parameters from the S2WFGCn interface. I just use whichever S2WFGCn interface has the right number of type parameters.
    For each type in the annotation, if it is generic, I just read the next type argument from the S2WFGCn superinterface and use that instead (but error if its raw type is not the same as the annotation value). Each S2WFGCn actually extends S2WFGC, which makes it easy to find the S2WFGCn amongst (possibly other) superinterfaces.
    The S2WFGCn interfaces are sort of marker interfaces, but as well as having no methods, they also have no meaning. They are more like a variable for holding an array of types at the meta level.
    Sorry, but thats the best I can come up with. Its not pretty for sure, and I'd rather have a nicer mechanism, but for this application at least, the benefits are still positive, since in most cases there are no generic classes, so all the trickery disappears, and when there are generics, the ends justify the means.
    If only the JSR-175 EG had realised that generics was a meta type of the language...
    This was their biggest failure by a country mile.

  • Problem with generics in general framework

    Hi,
    I've just started using generics and I've been able to solve most of my problems with type declarations etc, but I still have a few problems left.
    My current problem is in a class which has a map of classes which implements a generic typed interface (The interface is called Persister in the code below).
    The map is declared as:
    private Map<Class<?>, Persister<?>> persisters =
              new HashMap<Class<?>, Persister<?>>(); And the interface is declared as:
    interface Persister<T>My problem is that a method in the class which has the map should return a Collection of type T.
    Can that be done without supressing warnings?
    It's probably hard to understand what I mean (since I don't know the terminology) so here's a complete minimal example which illlustrates the problem. The problem is in the selectAll method in the DbFacade class.
    The lines:
         Persister persister = persisters.get(clazz);
         Collection<E> result = persister.selectAll(clazz);Needs to be altered but to what? (Or do I need to make more changes?)
    Thanks in advance
    Kaj
    ///////////////// Start of complete example
    import java.util.*;
    class ClientSample {
         public static void main(String[] args) {
              DbFacade facade = new DbFacade();
              //Works..
              Collection<Holiday> holidays = facade.selectAll(Holiday.class);
    class DbFacade {
         //Map with many different type of persisters,
         //one persister per class.
         private Map<Class<?>, Persister<?>> persisters =
              new HashMap<Class<?>, Persister<?>>();
         DbFacade() {
              persisters.put(Holiday.class, new HolidayPersister());
         //This is where I'm stuck
         //I don't want to add supresswarnings to this method, so what should I do?
         public <E> Collection<E> selectAll(Class<E> clazz) {
              //The following line gives:
              //Persister is a raw type. References to generic type
              //Persister<T> should be parameterized
              Persister persister = persisters.get(clazz);
              //The following line gives:
              //Type safety: The expression of type List needs unchecked
              //conversion to conform to Collection<E>
              Collection<E> result = persister.selectAll(clazz);
              return result;
    interface Persister<T> {
         List<T> selectAll(Class<T> clazz);
    abstract class AbstractPersister<T> implements Persister<T> {
    class HolidayPersister extends AbstractPersister<Holiday> {
         public List<Holiday> selectAll(Class<Holiday> clazz) {
              return null;
    class Holiday {
         //data
    }

    Well you can put in a type cast
    Persister<E> pesister = (Persister<E>) persisters.get(clazz);but you'll stil get a warning. Sometimes there's just no avoiding them. What, AFAIK, you can't tell the compiler is that each entry of the map contains a persister for the class mapped to it.
    All it knows that classes are mapped to Persisters.

  • Implementing DOM Interface with existing Java classes

    I had planned on using some tree-like Java classes as a Document Object Model, which would give me access to all sorts of XML and DOM tools like parsers and XSLT transformers. Initially, I thought all that would be neccessary is to implement all the DOM Interfaces in org.w3c.dom and then I would have a set of classes that conformed to DOM Level 1. It was my understanding that interfaces such as DOMImplementation and Document would interface with various XML tools, allowing creation of a class that implements Document and then Document would have its various factory methods that know how to create the various DOM nodes such as Element, Attr, Text, NamedNodeMap, NodeList, etc.
    The problem I'm seeing now is that the JAXP specification (which is what the latest Xerces and Xalan tools conform to) has something called a DocumentBuilder and DocumentBuilderFactory that appear to be necessary to tell the framework what type of class to instantiate that implements the Document DOM interface. Those appear to have a lot of methods that deal with parsing of XML documents and I didn't really want to write or even subclass any existing Parsers in order to get the functionality of traversing and transforming a set of classes that implement the DOM interface.
    Am I missing something here? Is it possible to plug in any (set of classes for) DOMImplementation and get them to work with the various DOM and XML tools out there?
    Is there an easier way to allow parts of an application access to internal data structures but have the more generic tools or APIs, such as XSL transformers, access that same set of classes as a DOM with the generic DOM interface methods?
    Can someone provide me with some guidance here? I'm in the process of finalizing some design on a system and need to know if this is possible or if I need to alter my design.
    Thanks.

    If I understand you correctly, I think I am working on a similar issue. I am unhappy with the methods given by the DOM for retrieving data from the XML file and for building a file. Our software has a bunch of code that uses these classes and it is extremely ugly. My solution was to create a facade on top of the DOM model. Essentially I have some simple classes that store all the pertinent info (for me) about the XML structure. Essentially that is the element or attribute name, its values and in the case of the element, it's children. This makes it easier for me to build and retreive the data. What I then built was a loader class and a builder class. The loader takes an XML file and parses it in using the DOM classes and builds a structure using my classes and returns the root element. The builder takes a root element and creates a DOM object out of it. This frees me of having to code around the DOM classes all over the place and makes it simple to upgrade our XML code if the DOM changes or a better DOM is released. I am using factories to facilitate this and allow me to have loaders for specific types of XML documents so that I can have a class for each which further simplifies the XML related tasks of other developers on my team.

  • Gerneric IDoc Interface

    Hi,
    We have the following set up:
    A JMS sender channel sends IDocs in a non XML format (some kind of flat file IDoc). I created a ABAP mapping that converts this flat IDoc to an XML IDoc. The problem is, that the sender sends diffrent kind of IDocs through the same channel.
    1.try: I imported all possible IDoc types and tryed to do a content based routing. The problem is the input message. Due the fact, that this is no XML on input side, I cannot check the input data. Is there a possibility to do content based routing AFTER the mapping?
    2.try: I created a dummy IDoc interface. The message type is just one tag (I created the complete IDoc XML in the ABAP mapping). So I send all data from the JMS to an IDoc receiver with the same dummy interface. The content of the receiver message contains all IDoc control data (EDI_DC40). The idea is, to use this interface as an generic IDoc interface but I get the error "ATTRIBUTE_WRONG_INTF" - "Unable to interpret IDoc interface MI_IDoc_any_IB_Async". Is there a way to set the IDoc attributes generic in the ABAP mapping or do I have to use the IDoc interface, that I imported?
    Thanks for your help
    JP

    1. The use of BPM may ease the routing part after mapping wherein u may use transform step folowed by send step
    2. While doing idoc communication, even if u change the structure, u ll have to use the interface name as the original imported idoc name only. Otherwise u ll get the same error.
    Regards,
    Prateek

  • Type casting in generics 2

    Is there any way to avoid casting in following code using generics.
    public Interface SomeInterface
    public class SomeClass implements SomeInterface
    public class SomeClass1
    public void meth(SomeInterface obj)
    SomeClass cls = (SomeClass) obj;
    }

    why would you want to cast the interface to the concrete class? if SomeClass implements SomeInterface, presumably it's because what your client code is interested in is SomeInterface, that's why we use interfaces. you can't be sure that obj is always going to be an instance of SomeClass, only that it's an instance of SomeInterface. If you could be sure, there'd be no point having the two types
    generics are a non-issue here

  • Message interface

    Hi all,
             In IDOC interface,
    sender is IDOC imported from R3
    Rec is same IDOC structure with my name space but i it is not created in IR.
    Interface mapping is done it is aying outbound it is saying name of IDOC(Order,order04) and at inbound side it is saying(Input message)...
    and interface working successfully from two years
    i try to click on the inbound interface with my namespace name it is saying unable to read this object..
    i try to understand this interface but i am missing some where
    ( one more thing actually this interface dont need any mapping but they created interface mapping)
    thanks
    Kumar....

    Hi Krishna,
    When ever u r doing the scenario with the IDoc either in the sender or in the receiver side there is no need to create the Inbound.Outbound Message Interface in the IR. U can directly import the IDoc to the XI and give the IDoc name directly to the inbound/outbound Interface.
    >>target is with the name space of interface but no interface is created in IR..
    Check if the Message Interface belongs to the same name space or to the some Generic Message Interface in the different namespace.
    Regards
    Santhosh
    Remember to set the thread to solved when you have received a solution

  • Referencing component usage with different interfaces

    Hi experts,
    First of, some details;
    - I'm on NW04.
    - I have a generic WDP interface named: IModelComponent
    - I have a specific WDP interface named: IEmployee
    - I have a WDP component implementing both interfaces named: Employee
    Now I want to create some sort of component factory component. In this component I have:
    - defined 'Used Web Dynpro Component' IModelComponent
    - Created a method getComponentUsage (static names just for clearer example):
    wdThis.wdGetIModelComponentComponentUsage().createComponent("x.x.x.org.mdc.empl.EmployeeModelComponent", "x.x/x~org~mdc~employee");
    return wdThis.wdGetIModelComponentComponentUsage();
    Next I have a client view component which refers to the component factory and the employee interface
    - defined 'Used Web Dynpro Component' IEmployee
    - defined 'Used Web Dynpro Component' ComponentFactory
    - On request I call the factory method getComponentUsage
    Now, when I use this component usage the following way:
    wdThis.wdGetIEmployeeComponentUsage.enterReferencingModeUnsafe(receivedComponentUsage);
    Then things work perfectly! This is basically what I want to achieve.
    But the method enterReferencingModeUnsafe is deprecated, so I wonder if there are other, better ways to achieve usage referencing of components with multiple interfaces (create as one interface, use as the other interface).
    Looking forward to any comment.
    Grtz,
    Chris
    Edited by: Chris van de Wouw on Feb 6, 2010 5:20 PM

    Basically solved it myself. I'm now using the actual required component usage (IEmployee) as entry point for the factory, which will create the correct implementation component (based on configuration). For IModelComponent specific methods I can use the getInterfaceController() of the employee component usage class and cast it to the model component interface.

Maybe you are looking for

  • Error 1172 occurred when sending smtp email via labview

    I found these two useful vi example to send smtp email using Labview: http://decibel.ni.com/content/docs/DOC-7451 http://decibel.ni.com/content/docs/DOC-2401 However, I got error 1172 saying "No connection could be made because the target machine act

  • Can you watch video on a tv while charging your ipod at the same time?

    I was just wondering cause since you connect the av connection (to tv) to the bottom of the ipod, which is the same place where you connect the cable to charge it. . . can you do both simultaneously? thanks. -JD

  • I need a copy of the warranty for a 2009 Mac Book Pro?

    For the purpose of getting my cc company to pay for the replacement of the optical drive on my macbook pro which is out of warranty, I need a copy of the original warranty please.

  • How to catch SQLException in CMP bean

    Hi there, I am using CMP beans to set columns, one of which has referential integrity. Because the abstract set() method does not declare to throw SQLException, I can not catch SQLException in my session bean (which calls local CMP bean for creating

  • "entry point not found" erro when starting firefox

    When trying to load Firefox from my desktop I get an error that says "Firefox.exe - Entry Point not Found". And also "The procedure entry point NS_SetDIIDirectory could not be located in the dynamic link library xul.dll. Any help would be greatly app