Generics at method level

As we all know, in Java5.0, Sun introduced Generics. Now I used this at class level and at field method. However I tried using them at method level, but could not succeced.
I did a search on the internet and I found a very good article about generics. The url is the following: http://www-128.ibm.com/developerworks/java/library/j-djc02113.html
Scrolling to the bottom, I found out what I needed. the example on that website shows the following:class Utilities {
   <T extends Object> public static List<T> make(T first) {
     return new List<T>(first);
}However I tried to do this code in a method inside my project, but did not work at all.
Does any one know how I can do generics at method level. What I want to achieve is that you pass the class type you want to be returned as a generic at the method level.
regards,
sim085

Please before you check my code, check the example that there is in the article, that is the code I posted in my first post. I based all this on the information I read from the website, and since the source looks very reliable,, there is no need for me to doubt that it works!
I did a simple example, I am just using generics to get used to them ... Here comes the exampleimport java.util.*;
public class Test{
     private List<String> myList;
     public Test(){
          myList = new ArrayList<String>();
          <List>normalMethod();
     <T>public T normalMethod(){
          return null;
     <T>public static void staticMethod(){
     public static void main(String... args){
          <List>staticMethod();
          new Test();
}The exception throws is an exception you would see when the syntax is incorrect. However I do have Java5.0 and if you delete the methods and the method calls, but you leave the generics at the field level , the code would compile.
The exception throws are the following:C:\Documents and Settings\saquilina\My Documents\Test.java:21: illegal start of type
     <T>public static void staticMethod(){
           ^
C:\Documents and Settings\saquilina\My Documents\Test.java:32: <identifier> expected
}Now since in the example in that website they use a static method, I tried it also with a static method, but it did not work all the same :(
regards,
sim085

Similar Messages

  • How to implement method level authorisation in JSF

    Hi all,
    I am new to JSF 2. I have been able to implement authorization on my web pages, but I also want to implement it at the bean level. Does JSF 2 provide an in-built functionality to implement role-based authorization on bean methods? Or, I need to use some security frameworks (i.e. ACEGI)?
    Thanks in advance,
    Neeraj

    I am curious: can you explain WHY you want method level security? It seems woefully overkill and paranoid to me - server level security should be enough to keep out rogue code.
    Anyway for that level of security, the security measures built into the JVM should be used.
    [Java Security documentation|http://java.sun.com/javase/technologies/security/]
    You can also look into a security API like Spring security - be warned though, it has a steep learning curve.

  • 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.     

  • Method-level Locking

    (Here's another one):
    I'm unable to find a way to enable method-level locking in WebLogic.
    This kind of lock has the same semantics as a simple "synchronized" on the
    method level (which you cannot write as a bean developer). The advantage is
    that you've got thread-safe access to a method without expensively
    interfering with the transaction manager.
    So is this possible in WLS v6.1/v7.0?
    Regards,
    Pieter Van Gorp.

    I assume you are talking about entity beans. You can use the "Exclusive"
    concurrency strategy. Here is the link:
    http://e-docs.bea.com/wls/docs61/ejb/reference.html#1139340
    "Pieter Van Gorp" <[email protected]> wrote in message
    news:[email protected]..
    (Here's another one):
    I'm unable to find a way to enable method-level locking in WebLogic.
    This kind of lock has the same semantics as a simple "synchronized" on the
    method level (which you cannot write as a bean developer). The advantageis
    that you've got thread-safe access to a method without expensively
    interfering with the transaction manager.
    So is this possible in WLS v6.1/v7.0?
    Regards,
    Pieter Van Gorp.

  • "method level" serializable ServerSockets

    i don't understand why this code block can be serialized:
    public class Foo extends Thread implements Serializable {
      public void run() {
        ServerSocket servSok = new ServerSocket(9876);
        Socket sok = servSok.accept();
    }compare with this code block. as expected it cannot serialize (unless transient is used):
    exception code = " +NotSerializableException: java.net.ServerSocket+ "
    public class Foo extends Thread implements Serializable {
      private ServerSocket servSok = null;  // <-- add "transient" and ok.
      public void run() {
        this.servSok = new ServerSocket(9876);
        Socket sok = servSok.accept();
    note: both are live, running, threads when serialized.
    one is an instance level object, the other a method level. but i cannot take my understanding
    beyond that. can someone talk me through what is going on?
    both are bound ServerSockets . neither can pop-up, after de-serialization, bound to a port
    on a remote jvm.

    pdFrog wrote:
    Your misunderstanding is that methods do not get serializedok. i did not know that.
    i think this is why we need the class loaders.Mneh, in a roundabout way, but probably not the way you're thinking. Technically speaking, methods are already serialized, in that their bytecode exists as a stream. But if you're trying to serialize code, not just data, you've probably misunderstood why we serialize. In particular, serializing a Socket connection of any kind is a bit pointless.

  • Method-level ACLs

    Can anyone provide me with an example web.xml file that has acl protection at the method level? There is documentation saying that you can protect down to the method level, but I am having trouble finding anything on how...

    I assume you are talking about entity beans. You can use the "Exclusive"
    concurrency strategy. Here is the link:
    http://e-docs.bea.com/wls/docs61/ejb/reference.html#1139340
    "Pieter Van Gorp" <[email protected]> wrote in message
    news:[email protected]..
    (Here's another one):
    I'm unable to find a way to enable method-level locking in WebLogic.
    This kind of lock has the same semantics as a simple "synchronized" on the
    method level (which you cannot write as a bean developer). The advantageis
    that you've got thread-safe access to a method without expensively
    interfering with the transaction manager.
    So is this possible in WLS v6.1/v7.0?
    Regards,
    Pieter Van Gorp.

  • JDeveloper 11 ignores @SuppressWarnings at method level

    Seems that this only works at class level.
    If you add it at a method level, JDev simply ignores it and continues to display warnings.
    Has anyone found how to get it to work?

    Hi,
    This is the code:
    <snip>
    @SuppressWarnings("unchecked")
    public List<T> findAll(final int... rowStartIdxAndCount)
    return commonPersistence.findAll(getClassName(), rowStartIdxAndCount);
    <snip>
    If I add this annotation to the line just before declaration of the class, it actually works, but becomes reasonably useless as I don't see any other warnings for the class.
    Thanks
    Jonny

  • JAAS method level authorisation

    Hi
    Is it possible to do method level authorisation in java.
    I was under the impression you grant permission at the class level. Can you please inform as to
    how we can grant permissions at method level.
    example :
    class A {
    method1();
    method2();
    can I grant permissions to A.method1() to execute, without having to create an actions class
    with run implemented as required , that is :
    class actionMethod1() implements PrivilegedAction {
    run(){
    A.method1();
    because then I will have to create too many action classes !

    Hi, try this:
    Within method 1 of Class A, do a permission check at the beginning of the method.
    Class A {
    1. public void method1() {
    2. SecurityManger sm = System.getSecurityManager();
    3. if(sm!= null ) {
    4. sm.checkPermission( new XXXPermission() );
    5. }
    6. }
    where XXXPermission is the type of permission that your checking for. If the current thread doesn't have this (XXXPermission) permission, then a SecurityException will be thrown and the rest of the method will not be executed. Alternatively, I believe that the above code (line 2-4) can be replaced with :
    1. AccessController.checkPermission(new XXXPermission());
    I hope this helps. You can also try referring to: http://java.sun.com/j2se/1.4/docs/api/java/security/AccessController.html
    >
    Hi
    Is it possible to do method level authorisation in
    java.
    I was under the impression you grant permission at the
    class level. Can you please inform as to
    how we can grant permissions at method level.
    example :
    class A {
    method1();
    method2();
    can I grant permissions to A.method1() to execute,
    without having to create an actions class
    with run implemented as required , that is :
    class actionMethod1() implements PrivilegedAction {
    run(){
    A.method1();
    because then I will have to create too many action
    classes !

  • JAWIN & its generic "Invoke" method

    Hi all,
    I'm currently using JAWIN to invoke a function from a 3rd party C++ DLL.
    The C++ function takes 0 input arguments and returns an argument of type char *.
    The problem is, I'm not exactly sure how to use the generic "Invoke" method, in particular the 'instructions' argument.
    public byte[] invoke(java.lang.String instructions,
    int stackSize,
    int argStreamSize,
    byte[] argStream,
    java.lang.Object[] objectArgs,
    ReturnFlags flags)
    throws COMException
    Can anyone shed some light on this? Thanks very much in advance.

    Hi,
    Is it really a C++ DLL ?
    How have you created an instance of your C++ class ?
    I'm very interested with this since I can't do it with JNative (the new MyObject()).
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to use generic webservice methods in java

    Hi,
    I am working on jdk1.5 and axis web service client version 1.3.
    I am calling webservice which developed in wcf service using .net ,Extesion like .svc?asmx
    input of webservice method is generic like list<IEmployee>
    When i try to call in cleint side , it is showing like object[] array.
    but it has to show like list<object>
    May i know solution for this.
    Thanks,
    Murali

    Hi konanki,
    Web services are using SOAP as protocol and SOAP has been designed for interoperability between computers installed with different platforms : Java, .Net, PHP, ...
    As List<IEmployee> or List<Object> are specific to Java language, they are translated in a way understandable for other platforms. Just have a look to your WSDL file.

  • Generic forwarding methods with recursive bounds.

    Hello all,
    I'm attempting to create a forwarding class assoicated with an interface. The interface has a generic method with recursive bounds. The problem relates to ambiguous method calls as the following code segment should demonstrate:
    interface TestInterface
        //generic method with recursive bounds. (use of Comparable<T> is
        // not relevant, any generic class/interface could have been used.)
        <T extends Comparable<T>> T testMethod(T bob);
    //Concrete implementation of the TestInterface.
    class TestClass implements TestInterface
        public <T extends Comparable<T>> T testMethod(T bob)
           return bob;
        public static void main(String[] args)
            TestInterface bob = new TestClass();
            bob.testMethod("blah"); //Works fine.
    class ForwardingClass implements TestInterface
        //Forwarding class composed of a TestClass object. All methods forward calls to this object.
        private final TestClass test;
        public ForwardingClass(TestClass test)
            this.test = test;
        //forwarding method.
        public <T extends Comparable<T>> T testMethod(T bob)
            return test.testMethod(bob);   //Ambiguous testMethod call. Both testMethod (T) in TestClass
                                           //and testMethod (T) in TestInterface match. Very annoying...
        }Therefore, if you could assist with the following issues, it would be greatly appreciated.
    Firstly, I don't think I fully understand why this error is given, so any explanation would be greatly appreciated.
    Secondly, is there any way to get around the problem?
    Thanks in advance,
    Matt.

    My bad. This appears to be an issue with Intellij 8.0M1. I'll create post on the Intellij forums. It compiles absolutely fine from the command line, and using Intellij 7.04. (Probably should have checked that before my initial post...)
    Apologies for wasting your time. Cheers for the replies.
    Matt.

  • 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);
    }

  • How do I create this generic enumeration method?

    I am storing enumeration values as classname/name. When I come to read them back in I have the following code:     public Enum<?> asEnum (String className, String value) throws ClassNotFoundException, ClassCastException {
              return Enum.valueOf (Class.forName (className).asSubclass (Enum.class), value);
         }But I get a warning on the valueOf call:"unchecked method invocation: <T> valueOf(java.lan.Class<T>,java.lang.String) in java.lang.Enum is applied to (java.lang.Class<capture of ? extends java.lang.Enum>,java.lang.String)"I don't really understand the warning, if I'm honest ... is there any way to re-write this method so that it compiles without insults?

    if I understand your program correctly then you are
    trying to load ANY class and treat it
    as subclass of Enum without any checking. Of course
    and thank you God, that's not
    possible in Java. Please try this: Well, it is not safe, but the original code demonstrates that it is possible. The code you wrote doesn't seem to do anything the valueOf() method doesn't already do:
    public final class CookEnum {
        enum Directions {
            NORTH, SOUTH, EAST, WEST;       
        public static void main(String[] argv) {
            Directions d = Enum.valueOf(Directions.class, "EAST");
            System.out.println(d);       
    }It is not possible to write the function RGibson wants because he is trying to start with a String containing a class name and get to an enum instance without any warnings. This can't be safe because as andrejin says, the String could be anything at all, and it isn't known until runtime, so how could the compiler ever check it?
    RGibson: if you insist on writing the code this way, I don't think there's a way to avoid the warning. It was recently indicated in this formum that @SuppressWarnings is unlikely to be implemented on any Java5 release.
    Two design questions: do you really need to be able to reconstitute any arbitrary enum type? If you can know the class at compile time, you can reconstitute the enum for its name easily.
    Secondly, is there a reason you're resisting using serialization to persist and recreate the enum? I believe using serialization does mean you can't remove or re-order the enum constants in the future without breaking compatibility or writing custom code, but you can add new values to the end of the set.
    Or are you trying to persist the enums to some medium where you need a purely textual representation like a user readable config file?

  • Generic sort method

    my method take any collection class as parameter and sort the list and return that sorted class.
    Here is my code
    public static <T extends Comparable<? super T>> Collection sort(Collection<T> col)  {
            Collections.sort(col);
            return col;
        }while compiling its getting following error:
    cannot find symbol method sort (java.util.Collection<T>)can any one tell me what is the wrong in my code.

    victorygls wrote:
    no, thats not a wrong, sort method is in Collections class onlyWait, sorry, I thought you were calling Collection.sort(...) without the s.
    But if you look at the Collections class, you will see that there is no sort(Collection) method. There are a couple of sort(List) methods though.

  • Generics, factory methods and compiler warnings

    Hi all,
    I have a parametrized class where new objects are created via a factory. The problem is that I'm getting some compiler warnings. Am I missing something or there's no way to avoid them?
    public interface Schedulable {
    // methods here
    public class Scheduler<T extends Schedulable> {
       // should this be parameterized? If yes, how?
       // (it's not possible to use T while <? extends Schedulable> gives problems)
       private static Scheduler scheduler;
       private NodeManager nodes;
       private DefaultServiceManager<T> services;
       private Timer timer;
       private LifecycleManager lifecycle;
       public static synchronized <E extends Schedulable> QueueScheduler<E> newInstance() {
              if (scheduler == null) {
                 scheduler = new Scheduler();
                scheduler.nodes = DefaultNodeManager.newInstance(scheduler);
                scheduler.services = new DefaultServiceManager<E>(scheduler.nodes);
                scheduler.timer = new Timer(scheduler);
                scheduler.lifecycle = new LifecycleManager(scheduler,
                       scheduler.timer);
                // these fields are initialized here and not into the constructor in order to avoid
               // the 'this' reference to escape (see   //http://www-128.ibm.com/developerworks/java/library/j-jtp07265/index.html
               // for example)
             // all the fields initialized above generate a warning
              return scheduler;
         protected Scheduler() {
              // initialization of some fields here
       // methods here
    // methods here
    }Thanks,
    Michele

    Oops, sorry, didn't see the variable actually is a static, raw one. Here you will have a problem, as for once you cannot use the E for the static variable and second you could not guarantee that a previously created Scheduler would have the same type parameter as the one you are going to create:FirstSchedulable a = Scheduler.newInstance();
    SecondSchedulable b = Scheduler.newInstance(); // would fail!The second call would fail, as the first would have created an instance of Scheduler<FirstSchedulable>, which is stored in the static variable scheduler and not compatible to a Scheduler<SecondSchedulable>.
    You should rethink you design.

Maybe you are looking for