Results 1 to 3 of 3
  1. #1
    eva
    eva is offline Member
    Join Date
    Dec 2007
    Posts
    49
    Rep Power
    0

    Default Writing generic methods

    Hi,

    I am writing an application in which I have following 4 methods:

    Java Code:
    int startProcess(int a) { ... }
    String startProcess(String a) { ... }
    float startProcess(float a) { ... }
    I want to declare a method that should be generic and that should serve all the purposes.

    Please advice.

    - PEACE

  2. #2
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Wink Generics

    Hello eva.

    How about using objects of instance Object. Like:
    Java Code:
    public static Object startProcess(Object a) {
        //Todo
        return null;
    }
    You can then use casting to get the correct data type depending on what you want to do. To implement this method, you will need to use the instanceof keyword. For example:
    Java Code:
    public static Object startProcess(Object a) {
        // Handel if it is a String
        if (a instanceof String){
            String aString = (String) a;
            // Do something to aString
        }
        return aString;
    }
    I hope this helped.
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

  3. #3
    spoon! is offline Member
    Join Date
    Dec 2007
    Posts
    12
    Rep Power
    0

    Default

    it would help more if you told us what this method should do
    you could use generics like this:
    Java Code:
    public static <E> E startProcess(E a) { ... }
    but you won't be able to do very much with the argument unless you know what type it is

Similar Threads

  1. Replies: 0
    Last Post: 04-07-2008, 08:14 PM
  2. Generic array
    By eva in forum New To Java
    Replies: 3
    Last Post: 12-23-2007, 12:12 AM
  3. Generic Hashtables
    By ShoeNinja in forum New To Java
    Replies: 0
    Last Post: 12-04-2007, 10:43 PM
  4. Generic Eclipse Modeling System 3.0 RC1
    By JavaBean in forum Java Software
    Replies: 0
    Last Post: 10-25-2007, 04:25 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •