Generic interface methods

The problem is that I want a generic interface that has a method that returns type T. And concrete implementations specify the type T and the method body.
Given the interface and class below, why do I get an unchecked conversion warning, and how do I eliminate it? Or is there an alternative?
Warning displayed by eclipse:
Type safety: The return type String of the method convert(String) of type AsciiStringConverter needs unchecked conversion to conform to the return type T of inherited method.
This code compiles...
public interface StringConverter<T>
    public T convert(String string);
public class CharacterValueConverter implements StringConverter<int[]>
    public int[] convert(String string) //unchecked conversion warning
        int[] values = new int[string.length()];
        for (int i = 0; i < string.length(); i++)
            values=(int)string.charAt(i);
return values;
Thanks,
C.

Here is the code that is used to test the CharacterValueConverter...
public class Test
    public static void main(String[] args)
        int[] values = new CharacterValueConverter().convert("abc");
        for(int i : values)
            System.out.println(i);
}

Similar Messages

  • Specialized vs. Generic Interfaces?

    Hi,
    I am new to these forums, please let me know if this is already part of a FAQ or not the appropriate place to ask this question.
    When designing an interface, would you recommend specialized or Generic Interfaces?
    As I am not sure if makes any sense, here are the two thinkings I have to define a myObject.getExportOptions() method that would return the ExportOptions that can be applied (i.e. "setCharacterDelimiter" for CSV export, "setHeader" for PDF, HTML....)
    Option 1:
    the code looks like:
      myObject.setExportMode(MICROSOFT_EXCEL);
      myExportOptions = (ExportOptionsExcel) myObject.getExportOptions();where the getExportOptions() would be defined as
    ExportOptions getExportOptions(); with the ExportOptions interface only defining all the common export options to all the export methods (PDF, Excel, HTML, Text...). And then to get to the export options that are specific to an export format, you would have to cast the object to a specific interface which extends the "generic" interface.
    Option 2:
    the code looks like:
      myObject.setExportMode(MICROSOFT_EXCEL);
      myExportOptions = myObject.getExportOptions();where the getExportOptions() would be defined as
    ExportOptions getExportOptions();with ExportOptions defining all the export options accross all the export methods (PDF, Excel, HTML, Text...). But if you tried to call the ".setExcelFormat(EXCEL_95)" method when the ExportMode is set to "TEXT_ONLY" then an exception would be raised (maybe something like "ExceptionNotApplicableToExportFormat").
    I did not find any document describing the prefered method of building this.... Any idea?
    Thanks,
    MonLand.

    I think I was not clear enough in my first message. Let me try to re-explain with a little bit more details (and more pseudo-code).
    Option 1:
    myReport.setExportMode(MICROSOFT_EXCEL);
    ExportOptions myExportOptions = myObject.getExportOptions();
    myExportOptions.setExportFileName("myReport"); // This would be common to any "export format" Now, for the "Excel" specific parameters, I would have to cast the options:
    ExportOptionsExcel myExcelExportOptions = (ExportOptionsExcel) myExportOptions;
    myExcelExportOptions.setExcelFileFormat(EXCEL_97);From the implementation point of view, I can have one "generic" ExportOption class/interface that contains all the common export properties. In addition, three or more classes that implement the specific export settings (one for Text_ONLY; one for MICROSOFT_EXCEL; one for PDF.....). From the developer point of view, to be able to set the "specific" properties, they have to know what interface to cast the export options to (because in the background, the reportObject class would create/return the "right" export options based on the export format that was set).
    Option 2:
    This time the ExportOptions is a much more generic interface and declares everything. But an exception is raised if I am trying to set parameters that don't make sense:
    myReport.setExportMode(MICROSOFT_EXCEL);
    ExportOptions myExportOptions = myObject.getExportOptions();
    myExportOptions.setExportFileName("myReport"); // This would be common to any "export format"
    myExportOptions.setExcelFileFormat(EXCEL_97);Now, if I was to do:
    myReport.setExportMode(TEXT_ONLY);
    ExportOptions myExportOptions = myObject.getExportOptions();
    myExportOptions.setExportFileName("myReport"); // This would be common to any "export format"
    myExportOptions.setExcelFileFormat(EXCEL_97);This last line would raise an exception (let's say "UnsupportedProperty") because the Text mode does not support the ExcelFileFormat property.
    From the implementation point of view, I can have three or more classes that implement the "ExportSettings" interface (one for Text_ONLY; one for MICROSOFT_EXCEL; one for PDF.....). But from the developer point of view, it does not matter with class gets used.
    Why I am asking: I am currently facing a design that looks like Option 1 and I can not figure out why this has to be that complex to use. Very hard to document if you replicate that design everywhere in a large API with a large number of objects/interfaces; you never know what to cast the object to; you never can guess what method you are looking for because you have to look at the definition of 3 or 4 interface at the minimum to see if you see something that fits your needs. So I am trying to understand if this is because it is much easier to implement that Option 2.
    I see the following drawback for Option 2: If you need to add an extra property to one of the export format, you probably have to update the "generic" interface, the "generic" implementation of that interface, and each "specific" implementation to reflect that new property.
    Thanks a lot for your time!
    MonLand

  • Generic interface in abstract super class

    hello java folks!
    i have a weird problem with a generics implementation of an interface which is implemented in an abstract class.
    if i extend from this abstract class and try to override the method i get this compiler error:
    cannot directly invoke abstract method...
    but in my abstract super class this method is not implemented as abstract!
    do i have an error in my understanding how to work with generics or is this a bug in javac?
    (note: the message is trown by the eclipse ide, but i think it has someting to do with javac...)
    thanks for every hint!
    greetings daniel
    examples:
    public interface MyInterface <T extends Object> {
       public String testMe(T t);
    public abstract class AbstractSuperClass<T extends AbstractSuperClass> implements MyInterface<T> {
       public String testMe(T o) {
          // do something with o...
          // now we have a String str
          return str;
    public final class SubClass extends AbstractSuperClass<SubClass> {
       @Override
       public String testMe(SubClass o)
          return super.testMe(o);
    }

    Hi Wachtda,
    Firstly, T extends Object is redundant as all classes implicitly extend the Object class.
    Therefore :
    public interface MyInterface <T> {
       public String testMe(T t);
    }Secondly, abstract classes may have both abstract and non-abstract instance methods. Also, two methods, one abstract and one non-abstract, must have a different signature.
    The following example will give a compile error because the methods share the same signature :
    abstract class Test {
         public void sayHello() {
              System.out.println("Hello");
         abstract public void sayHello();
    }Therefore, to make an interface method as abstract would simply block the possibility of implementing it.
    BTW, you can do this :
    abstract class Test {
         public void sayHello() {
              System.out.println("Hello");
         abstract public void sayHello(String name);
    }Finally, there's no bug in javac.

  • Writing generic interfaces?

    I would like to write a generic interface for a Factory. The implemented Factory should as minimum contain two methods that returns a List of "something" as seen below.
    But I don't want to put any restrictions on the return type since a user might want to use objects from his or her own API. Is the solution to just specify the interface as:
    public interface IReportFactory {
         List newProducts();
         List newTables();
    }

    Here's a small example to guide you. Good luck my friend...
    import java.util.*;
    public class Test
         public static void main(String... args)
              List<Product> prodList = new ArrayList<Product>();
              prodList.add(new Product("radio", 100)); prodList.add(new Product("Walkman", 50));
              List<Table> tableList = new LinkedList<Table>();
              tableList.add(new Table("customer", 100)); tableList.add(new Table("Product", 1000));
              Report r = new Report(prodList, tableList);
              System.out.println("Products\n----------\n"+r.newProducts());
              System.out.println("Tables\n----------\n"+r.newTables());
              System.out.println("\nChanging Structures to Vector and Stack\n");
              prodList = new Vector<Product>();
              prodList.add(new Product("radio", 100)); prodList.add(new Product("Walkman", 50));
              tableList = new Stack<Table>();
              tableList.add(new Table("customer", 100)); tableList.add(new Table("Product", 1000));
              r = new Report(prodList, tableList);
              System.out.println("Products\n----------\n"+r.newProducts());
              System.out.println("Tables\n----------\n"+r.newTables());
    class Product
         String name; double price;
         Product(String n, int p){ name = n; price = p;}
         public String toString(){ return "\nName = "+name+" & Price = "+price+"\n";}
    class Table
         String name; int numRecs;
         Table(String i, int v){ name = i; numRecs = v;}
         public String toString(){ return "\nName = "+name+" & # of Records = "+numRecs+"\n";}
    class Report<T, V> implements IReportFactory<T, V>
         T prodList;
         V tableList;
         Report(T prodList, V tableList)
              this.prodList = prodList;
              this.tableList = tableList;
         public T newProducts()
              return this.prodList;
         public V newTables()
              return this.tableList;
    interface IReportFactory<T, V>
         T newProducts();
         V newTables();
    }

  • Implementing two generic interfaces

    I have a generic interface,
    public interface Callback<R> {
       void result(R r);
    }Now I want to implement two Callback interfaces, like this
    class X implements Callback<Type1>, Callback<Type2> {
       public void result(Type1 r) {};
       public void result(Type2 r) {};
    }But Eclipse tells me "The interface Callback cannot be implemented more than once with different arguments".
    I don't see the reason why really. The two overloaded result methods have different signatures so there shouldn't be any problem in resolving the correct one based on parameter type in principle.
    Does anybody know the reason for this restriction or is it maybe an issue with Eclipse. I'm using Eclipse 3.2M5a and Java 6.0 beta.

    mlk has the correct answer, but here's some more explanation:
    Generics are only used at compile time. The actual bytecode specifies the base object type (aka type erasure), in this case Object. When you implement a generified interface, the compiler will generate a bridge method from the erased type to the specific type.
    Some examples should make this clearer.
    First, your interface. If you run javap on the compiled class, you'll see that it only defines a single method, "void result(Object)".
    Code that invokes the interface, like this:
        Callback<String> foo = \\
        foo.result("bar");also gets translated to a call on the base type. As far as the compiled class is concerned, there is no type safety. However, the compiler will complain if you pass something other than a String.
    The implementation class is where things get interesting:
    public class TestCallback implements Callback<String> {
      public void result(String x) {
    }If you run javap on this class, you'll see that it contains two implementations of result(): one that takes a String, and one that takes an Object. If you look at the bytecode, the latter performs a cast on the Object and invokes the String variant.

  • Calling an interface METHOD of another abap web dynpro application

    Hi Experts,
    Can u plz tell how we can Call an interface METHOD of another abap web dynpro application in main WD Component.
    Thanks
    Mahesh

    Hi ,,
       Example ALV interface method calling   GET_MODEL interface method
       View attribute   declaration   :    M_WD_ALV  type      IWCI_SALV_WD_TABLE
         DATA lo_INTERFACECONTROLLER TYPE REF TO IWCI_SALV_WD_TABLE .
          wd_this->M_WD_ALV =   wd_this->wd_cpifc_alv( ).   "ALV is the usage name
         DATA lv_value TYPE ref to cl_salv_wd_config_table.
          lv_value = wd_this->M_WD_ALV->get_model(  ).   " interface method calling in ALV component usage.....
    Regards,
    Devi

  • Access specifiers for interface methods

    When we implement the interface ,we have to specify the implementing method access specifier to be "PUBLIC" ,but not "PROTECTED" or "PRIVATE".
    Compiler is giving an error -- attempting to assign weaker access privileges ,when we specify protected.
    what is the internal reason for this?Why we shouldnt make the access weaker in the implementing class.
    Can any one help me on this.Your help is highly appreciated.

    When we implement the interface ,we have to specify
    the implementing method access specifier to be
    "PUBLIC" ,but not "PROTECTED" or "PRIVATE".
    Compiler is giving an error -- attempting to assign
    weaker access privileges ,when we specify protected.
    what is the internal reason for this?There is absolutely no point in having a private interface method. The interface represents a visible abstraction and private methods are never visible so it is a contradiction in terms.
    An interface is intended to represent an abstraction that a user (software) uses. Protected via child/parent represents a usage that is restricted to a child from a parent. The child can already see the parent so there is no point in having an abstraction for the child. And it would probably be unwise to limit a child by such an abstraction.
    Protected via the package and interfaces is more contentious as to why it is not allowed. There are those that argue that this should be allowed so that a package can use interfaces but restrict them to the package. To me this seems like a minor point given that most interfaces will probably represent an abstraction to other packages and not within a single package. This applies specifically to default access as well.

  • Interface Method

    Hi experts,
    I have the following scenario:
    Component A opens, in a modal window, the component B.
    When I do something in B, it's closed and I return to A.
    There, I need read data from B (which is closed at the moment), to do something in A.
    Anybody knows how can I do it?
    I tried with external context mapping, but It doesn't work...
    Could it be done with interface methods?
    Thanks in advance!
    Lucas

    Hi Padmam,
    Thank you for your reply too, but I'm having problems with your solution.
    I have created an interface Node in Component A, and I have created the mapping in the component usages of the component B.
    When I run component A, it gives me an error. I supose that it is rise by this Interface Node.
    This error is solved when I check out the property "Input Element (Ext)" of Interface Node, but without this property, I can't do the External Mapping...
    Could you correct me if I'm wrong?
    Thanks in advance!
    Lucas

  • Question when i am in web dynpro interface method trying to find code

    Hello guys,
    I am in an event handler and i see this logic wd_this->mo_dodm_srchbidder_c->add_selected_bidder().  When i double click on the add selected bidder it takes me to the method inside interface /sapsrm/IF_CLL_DODM_BIDDER.   So when i double click on the method it takes me nowhere.
    My question is what do i have to do or where do i go to see the code for add_selected_bidder?   thank you.

    I think, you have visited to the definition of the interface method and not the implementation of the method.
    You have instantiated the wd_this->mo_dodm_srchbidder_c some where, may be in the wd domodifyview. Find that out where the implementation happens.
    I believe when you double click the method in  editor ask for to go to definition or implementation.

  • Overriding Interface methods via JNI

    Hello,
    How we can override Interface methods via JNI?
    For example:
    At HelloWorldSwing example:
    http://download.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java
    I've written anonymous Interface as:
    import javax.swing.*;       
    public class HelloWorldSwing1 {
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Add the ubiquitous "Hello World" label.
            JLabel label = new JLabel("Hello World");
            frame.getContentPane().add(label);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        static Runnable runnableObject = new Runnable() {
             public void run() {
                  createAndShowGUI();              
       public static void main(String[] args) {
             //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            SwingUtilities.invokeLater(runnableObject);
    }via JNI functions(http://download.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html) we cannot override Runnable Interface's run method? Can we?
    Only:
    RunnableClass's value isn't null with given example at below. FindClass finds the Runnable Interface.
    jclass RunnableClass;
    RunnableClass = (*env)->FindClass(env,"java/lang/Runnable");
      if( RunnableClass == NULL ) {
        printf("can't find class Runnable\n");
        exit (-1);
      }But How can we override Runnable class's run method?
    Thanks in Advance

    The only way you can override a method in Java is by defining a class that does so, either statically or as an anonymous inner class. You can't do either of those things in JNI. Ergo you cannot do what you are asking about.

  • Accessing an app.module's client interface methods in other app module

    Hi all,
    We are developing an application with number of projects (one for each module). We have got a common project with an application module, entity and view objects which are common for the entire application. For reusability, this common project is shared in session scope since most of them are of static nature.
    In the shared application module's implementation class, a common method has been included that will be used for data filtering by constructing/appending where clauses in a particular application scoped view object. This method has been exposed as client interface method so that other projects can make use of it. The common project is compiled as an ADF Library jar for accessing it in other projects.
    For accessing the exposed client interface method, from the view controller layer, we can include its reference in the page definition file and can execute the method from a managed bean by finding the operation binding from the page definition. But, in case if we wish to access the method in another model project, we could not do so.
    Now, my questions are:
    1. Is it the correct location(Shared App Mod. Impl) for including the logic to filter the data?
    2. Is it possible to access the app. module impl method in another project's impl classes (Let it be entityImpl or viewObjectImpl or viewRowImpl or AppModImpl) ?
    3. If it is possible, how it has to be done?
    Thanks and regards,

    Strange, the same question here {thread:id=2187487}
    Timo
    Edited by: Timo Hahn on 08.03.2011 12:02
    @john You beat me agian

  • Generic static methods in a parameterized class

    Is there anything wrong with using generic static methods inside of a parameterized class? If not, is there anything special about defining them or calling them? I have a parameterized class for which I'd like to provide a factory method, but I'm running into a problem demonstrated below:
    class MyClass<T> {
         private T thing;
         public
         MyClass(T thing) {
              this.thing = thing;
         public static <U> MyClass<U>
         factoryMakeMyClass(U thing)     {
              return new MyClass<U>(thing);
    class External {
         public static <U> MyClass<U>
         factoryMakeMyClass(U thing)     {
              return new MyClass<U>(thing);
    class Test {
         public static void
         test()
              // No problem with this line:
              MyClass<String> foo = External.factoryMakeMyClass("hi");
              // This line gives me an error:
              // Type mismatch: cannot convert from MyClass<Object> to MyClass<String>
              MyClass<String> bar = MyClass.factoryMakeMyClass("hi");
    }Does this code look ok to you? Is it just a problem with my ide (Eclipse 3.1M2)? Any ideas to make it work better?

    I've been working on essentially the same problem, also with eclipse 3.1M2. A small variation on using the external class is to use a parameterized static inner class. I'm new enough to generics to not make definitive statements but it seems to me that the compiler is not making the correct type inference.
    I think the correct (or at least a more explicit) way of invoking your method would be:
    MyClass<String> bar = MyClass.<String>factoryMakeMyClass("hi");
    See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ401
    See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ402
    Unfortunately, this does not solve the problem in my code. The compiler reports the following error: The method myMethod of raw type MyClass is no more generic; it cannot be parameterized with arguments <T>.
    Note that in my code MyClass is most definitely parameterized so the error message is puzzling.
    I would like to hear from more people on whether the sample code should definitely work so I would appreciate further comments on whether this an eclipse problem or my (our) misunderstanding of generics.     

  • Redefine Interface Method

    Hi, I am using a BI Interface "IF_RSCNV_EXIT" and I am adding code to the "Exit" Method. 
    Do I need to redefine this method?  The reason I ask is because the redefine icon is greyed out even though I am in edit mode.
    Thanks!

    Hello Kenneth
    Interface methods are always empty. You can implement them only once within a hierarchy of classes using this interface. Thus, you cannot redefine it.
    Regards
      Uwe

  • Interface method in enhancement mode

    Hello Experts,
    I need to enhance a standard web dynpro component. I have created a new method in the component controller using enhancement implementation. This method has to be called from another component. Therefore I need to make this as an interface method. But in enhancement mode I do not see an option to make this method as an interface mathod. Kindly let me know if this is poosible.
    Thanks,
    Pooja

    Hi Pooja,
    Please check this threads.. Hope you understand.
    Add an interface Method/Event via enhancement??
    How to make Interface node in an Enhancement Implementation
    Cheers,
    Kris.

  • Class/Interface/Methods

    Hi All,
    I'm trying to understand the concept behind abap class/interface/methods.
    1. Is it mandatory to have an interface in every class?
    2. Once a class is created is it right to define methods as static and public and use them without reference to the interface?
    Any help appreciated.
    Meghna

    hi meghna,
    interfaces in ABAP Objects play the same role as classes. Just like classes, interfaces are object types that reside in the namespace of all types. While a class describes all aspects of a class, an interface only describes a partial aspect
    The syntax for declaring a local interface is:
    INTERFACE intf.
       DATA ...
       CLASS-DATA ...
       METHODS ...
       CLASS-METHODS ...
    ENDINTERFACE.
    Basically, the declaration of an interface corresponds to the declaration part of a class, where instead of CLASSu2014ENDCLASS, you simply use INTERFACEu2014ENDINTERFACE. Interfaces can contain exactly the same components as classes. Unlike classes, however, interfaces don't need to be divided into different visibility sections because interface components are always integrated in the public visibility section of classes.
    i dont want to confuse you .
    please go to the below link to know more about... interface and classes.
    [http://help.sap.com/saphelp_nw04/helpdata/en/ec/d9ab291b0b11d295400000e8353423/frameset.htm]

Maybe you are looking for

  • Spam notification of Paypal payment on opening Sky...

    I have just purchased a Kindle Fire HD and spent a while yesterday lunchtime getting to grips with it.  I decided to load Skype on it so that I can keep in touch with friends and family via the web as I do not have a mobile phone. Imagine my horror l

  • Creaitve labs zen micro photo

    hi everyone ..... my daughter has been bought one of the micro photo zen 4gb i know iam asking what has prob been asked before...but can anyone tell me if this works with vista and will this have digital rights for the internet....can this be adapted

  • CS4 Tree view

    Hello, I created treeview in that each node contain 2 PMStrings name and adress. When i select perticular node in tree and click on delete button then selected node will be deleted from list. and also is their any method to interchange two node in tr

  • Issue accessing iPhoto!

    I have an issue with accessing iPhoto after I updated to OS X Yosemite, my computer doesn't even show iPhoto app. Does anyone know what might be the problem?

  • Internet Browsers Hijacked

    I've been using Firefox since I've owned my MacBook Pro. This morning I went to start up computer and initially all of me startup settings had defaulted (desktop image, dock style, dock applications, desktop files and apps). After restarting all seem