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.     

Similar Messages

  • In terms of scalabilty, will static method in normal java class better than

    You only have one copy of the static method in memory, but you have a few copy of the stateless session bean, plus the overhead of those session bean.So isn't static method of normal java class more scalable than stateless session bean.

    Then you have to take care of transaction management, connection pooling, etc other ejb services all by your self.
    In fact stateless session beans acts more like a static class. They do not get destroyed when remove() method is called on client stub. Similarly they are not always gets created whenever someone calls create() method on home interface!! (Again it's specific to appserver implementation)
    Thx.

  • Can we call a static method without mentioning the class name

    public class Stuff {
         public static final int MY_CONSTANT = 5;
         public static int doStuff(int x){ return (x++)*x;}
    import xcom.Stuff.*;
    import java.lang.System.out;
    class User {
       public static void main(String[] args){
       new User().go();
       void go(){out.println(doStuff(MY_CONSTANT));}
    }Will the above code compile?
    can be call a static method without mentioning the class name?

    Yes, why do it simply?
    pksingh79 wrote:
    call a static method without mentioning the class name?For a given value of   "without mentioning the class name".
        public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
            Class<?>[] types = new Class<?>[args.length];
            for(int i=0;i<args.length;++i) types[i] = args==null?Object.class:args[i].getClass();
    return Class.forName(className).getDeclaredMethod(methodName,types).invoke(null,args);

  • Static methods in data access classes

    Are we getting any advantage by keeping functions of DAOs (to be accessed by Session Beans) static ?

    I prefer to have a class of static methods that
    require a Connection to do their work. Usually, there
    is a SessionBean that 'wraps' this DAO. The method
    signatures for the SSB are the same, minus the need
    for a Connection, which the SSB gets before delegating
    to the Static Class.Uggh, passing around a connection. I've had to refactor a bunch of code that used this pattern. We had classes in our system that took a class in their constructor simply because one of their methods created an object that needed the connection. Bad news--maintenance nightmare--highly inflexible.
    What we've done is create ConnectionFactory singletons that are used throughtout the application in order to get connections to the database. All connection factory implementations implement the same interface so they can be plugged in from other components at runtime.
    In my opinion, classes that use connections should manage them themselves to ensure proper cleanup and consistent state. By using a factory implementation, we simply provide the DAO classes the means by which they can retrieve connections to the database and even the name of the database that needs to be used that is pluggable. The DAO classes do their own connection management.
    For similar reasons, I eschew the static method concept. By using class methods, you make it difficult to plug in a new implementation at runtime. I much prefer the singleton pattern with an instance that implements a common interface instead of a class full of static methods.
    I recently needed to dynamically plug in new connection factory implementation so that we could use JNDI and DataSources within the context of the application server (pooled connections) but use direct connections via the Driver manager for unit testing (so the application server didn't need to be running). Because of the way this was coded, I simply changed the original factory to be an abstract factory and changed the getInstance() method to return a different implementation based on the environment (unit test vs live). This was painless and didn't require changing a single line of client code.
    If I had to do this using the previous code that I refactored, I would have had to change about 200 jsp pages and dozens of classes that were making calls to the static method of the previous factory or hacked in something ugly and hard to maintain.
    YMMV

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Abstract class and a static method

    Can i call a static method within an abstract class ?

    public class AbstractDemo {
      public static void main(String[] args) {
        BiPlane biPlane = new BiPlane();
        System.out.println("biplane propulsion = " + biPlane.getPropulsionType());
        JumboJet jumboJet = new JumboJet();
        System.out.println("jet load = " + jumboJet.confirmMaxLoad());
        System.out.println("jet speed = " + jumboJet.getTopSpeed());
        System.out.println(Airplane.confirmMaxLoad());
    abstract class Airplane {
      static String confirmMaxLoad() {
        return "go_get_um, yeehaa!";
      public abstract String getPropulsionType();
      abstract String getTopSpeed();
    class BiPlane extends Airplane {
      public BiPlane() {
        System.out.println("BiPlane constructor");
      static String confirmMaxLoad() {
        return "400 lbs";
      public String getPropulsionType() {
        return "propeller";
      final String getTopSpeed() {
        return "130 knots";
    class JumboJet extends Airplane {
      public JumboJet() {
        System.out.println("JumboJet constructor");
      public String getPropulsionType() {
        return "jet";
      public String getTopSpeed() {
        return "mach .87";
    }

  • Why do we need private static method or member class

    Dear java gurus,
    I have a question about the use of private and static key words together in a method or inner class.
    If we want to hide the method, private is enough. a private static method is sure not intended to be called outside the class. So the only usage I could see is that this private static method is to be called by another static method. For inner class, I see the definition of Entry inner class in java.util.Hashtable, it is static private. I don't know why not just define it as private. Could the static key word do anything better.
    Could anybody help me to clear this.
    Thanks,

    What don't you get? Private does one thing, andstatic does >something completely different.
    If you want to listen to music, installing an airconditioner doesn't help>
    Hi, if the private keyword is the airconditioner, do
    you think you could get music from the static keyword
    (it acts as the CD player) in the following codes:You're making no sense and you're trying to stretch the analogy too far.
    Private does one thing. If you want that thing, use private.
    Static does something completely different and unrelated. If you want that thing, use static.
    If you want both things, use private static.
    What do you not understand? How can you claim that you understand that they are different, and then ask, "Why do we need static if we have private"? That question makes no sense if you actually do understand that they're different.

  • Why can't inner classes have static methods?

    I just tried to add a static method to an inner class, which would have been useful for extracting constants about said inner class, and it turns out that is not allowed.
    Of course I have other ways to code what I wanted, but I'm curious as to why this restriction was set in place. Anybody know?

    Probably because an inner class is tied to an instance of the enclosing class. I think that, conceptually at least, the inner class' definition itself only exists in the context of an instance of the enclosing class. While I'm sure it would have been technically possible to allow it, it would be confusing and not make a whole lot of sense--what is the static context for the inner class, since the class only exists in a non-static context?

  • Abstract static methods

    Hello,
    I've written an abstract class, called AbstractNetworkParticipant. I've also written two sub classes that extend this class. I'm in the process of writing a Viewer class that I'm intending to parameterized with some subclass of AbstractNetworkParticipant,
    public class Viewer<T extends AbstractNetworkParticipant> I would like to include a couple of static methods that return Strings for Labeling information to a particular subclass in the Viewer.
    So for example, if I have NetworkUser and NetworkAdministrator, both of which extend AbstractNetworkParticipant, I would like to set the text of a JLabel labeling the participant's name to "User Name", or "Administrator Name" depending on the type of participant being viewed.
    I would like the method that returns these strings to be static, so that I don't have to have an instance of the current subclass when I initializes the JLabel. An abstract method cannot be static. I attempted to make a non-abstract static method in the abstract class,
      public static getDescriptor() {
         return "Participant";
      }and then override it in each sub class to a more descriptive string (User, or Administrator). However, when I reference the method, it always invokes the method defined in the abstract parent class, rather than in the subclass, whichever it may be.
    Can anyone suggest a solution. Should I just forget about the method being static? Is there a better way to implement a solution to this problem?
    Thanks
    Edited by: paulwooten on Mar 27, 2009 9:58 AM

    paulwooten wrote:
    The whole point of my original post was in order to learn something about Java that I'm not particularly familiar with. I was having a difficult time articulating the problem precisely, so I tried to draw an analogy between C++ and Java. It turns out I was mistaken in the way C++ works. Fortunately I described my problem adequately enough to both 1. be corrected about how virtual functions actually work in C++, and 2. get advice on how to approach the problem in Java. I never claimed I was a C++ expert, or that I was asking a question about C++. I was just trying to explain my problem as precisely as possible.
    I don't mean to disrespect, but your post, and slimy's aren't nearly as constructive as all the other posts that actually addressed my question; either to me personally, or to anyone else who has a similar question and may happen to read this thread. It's not like I dumped a bunch of C++ code here and begged someone to translate it for me. I asked a question, to the best of my ability, several other forum members replied (without giving me a mini lecture on how to learn Java), and now the problem is resolved.Sorry for the confusion. I wasn't complaining about your post. My post wasn't directed at you at all. It's fine to know C++, and to ask how to do something similar in Java. As you said, that wasn't even how you asked your original question. You asked a legitimate question to learn Java, a few people made suggestions, you made a comparison to C++, and people corrected your understanding both of C++ and Java. That's all well and good, and it's a fair way to learn. I see no problem with any of that.
    What exactly does "learn Java properly" mean? Read the tutorials and pretend like no other programming languages exist?I was referring to slimy's post where he talked about "knowing C++ properly if you use it as an input to Java". The point of my post was supposed to be that "you can know C++ properly, but +you shouldn't always use that as your input to Java+". A very simple example I've seen of what I meant by "non-proper" Java code, in real [but +bad+ ] Java code at a real company is for String comparison:
    String abc = "abc";
    String xyz = "xyz";
    String another = "xyz";
    if (abc.compareTo(xyz) != 0) { // Not "proper" Java
       doSomething();
    if (xyz.compareTo(another) == 0) { // Not "proper" Java
       doSomethingElse()
    }To me, that looks like someone who copied their C++ knowledge (or, at least, C knowledge) to the extreme. In C, the only function to test equality of two C "strings"--i.e., "null-terminated char arrays" is 'strcmp', and you test equality of the strcmp result to 0 to determine whether two "null-terminated char arrays" represent the same thing:
    char abc [] = "abc";
    char xyz [] = "xyz";
    char another [] = "xyz";
    if (strcmp(abc, xyz)) { // could include explicit != 0, but not needed in C
       doSomething();
    if (!strcmp(xyz, another)) { // anything non-zero is true in C, so !0 is true
       doSomethingElse();
    }"compareTo" sounds like "strcmp", and the comparison to 0 is the same in my above examples.
    But, in Java, there is a real "equals" method for Strings, and it should be used:
    String abc = "abc";
    String xyz = "xyz";
    String another = "xyz";
    if (!abc.equals(xyz)) { // "proper" Java
       doSomething();
    if (xyz.equals(another)) { // "proper" Java
       doSomethingElse()
    }I would argue that using "compareTo" to test equality of Strings in Java is "non-proper" Java, and using "equals" to test equality of Strings in Java is "proper" Java. That was my definition of "learning Java properly".
    I certainly don't think anyone learning Java needs to pretend that no other programming languages exist--it is fine to know other languages, and to look for the similarities (and differences). However, someone learning Java (or any other language new to them) does need to know that things don't work the same in all languages, so, if they base all of their knowledge by trying to get Java to work exactly the same as C++ (or whatever previous language they knew), their Java will not be "proper" Java. There are often multiple ways to do things "properly" in Java, but copying a C++ program verbatim into Java syntax is not necessarily going to result in the best Java code that you could have. When doing the translation from another language to Java (I realize that isn't your goal, but for some people, that is the goal), you need to be sure that your Java code follows Java rules and standards, and not just assume that the architecture of your Java code should be the same as the architecture of your code in the original language.
    I hope that clarifies my intentions. As I said, I wasn't directing my previous comment to you. I think your question and learning approach are absolutely fine.

  • Using main class's methods from a different class in the same file

    Hi guys. Migrating from C++, hit a few snags. Hope someone can furnish a quick word of advice here.
    1. The filename is test.java, so test is the main class. This code and the topic title speak for themselves:
    class SomeClass
         public void SomeMethod()
              System.out.println(test.SomeOperation());
    public class test
         public static void main(String args[])
              SomeClass someObject = new SomeClass();
              someObject.SomeMethod();
         public static String SomeOperation()
              return "SomeThing";
    }The code works fine. What I want to know is, is there some way to use test.SomeOperation() from SomeClass without the test.?
    2. No sense opening a second topic for this, so second question: Similarly, is there a good way to refer to System.out.println without the System.out.? Like the using keyword in C++.
    Thanks.

    pfiinit wrote:
    The code works fine. What I want to know is, is there some way to use test.SomeOperation() from SomeClass without the test.?Yes you can by using a static import, but I don't recommend it. SomeOperation is a static method of the test class, and it's best to call it that way so you know exactly what your code is doing here.
    2. No sense opening a second topic for this, so second question: Similarly, is there a good way to refer to System.out.println without the System.out.? Like the using keyword in C++.Again, you could use static imports, but again, I don't recommend it. Myself, I use Eclipse and set up its template so that when I type sop it automatically spits out System.out.println(). Most decent IDE's have this capability.
    Also, you may wish to look up Java naming conventions, since if you abide by them, it will make it easier for others to understand your code.
    Much luck and welcome to this forum!

  • Can't get ClassLoader from static method.

    I'm trying to get the ClassLoader within a static method getInstance().
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless session bean, a null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in a standalone
    java program?
    Thanks for you help.
    Bernie

    Sorry for the confusion. I wrote a couple of more test programs and was able
    to confirm that WL behaves exacltly the same as java does. For some reason
    my intial tests were messed up...
    getClassLoader() executed from a static method always returns null (in WL as
    well as in a java standalone program).
    In this case ClassLoader.getSystemClassLoader() will return a valid class
    loader.
    Thanks for your help.
    Bernie
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    Bernhard Lenz wrote:
    I tried that as well, but getClassLoader() still returns null when
    executed
    in WL.
    I'm still not clear how getClassLoader() gets affected by running withinWL.
    >>
    >
    Very odd. Where is this class located? in the server's classpath, in ajar or
    war file? Does getClass().getClassLoader work from a non-static method inthis
    class?
    -- Rob
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    You want PropertyManager.class.getClassLoader()
    -- Rob
    Bernhard Lenz wrote:
    I'm trying to get the ClassLoader within a static method
    getInstance().
    >>>>
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless sessionbean, a
    null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in astandalone
    java program?
    Thanks for you help.
    Bernie

  • OOPs Concept ! - Why Static Methods can't be redefined in its subclass ?

    Dear Experts ,
    I had searched the SDN , but unable to find out the satisfactorily answers ..
    Can anybody let me know the reason for the following Confusion in Oops Concept
    Question 1: As we know , We can Inherit the Static Methods in the Sub Class , But we can't redefine it in the base class  or       Sub Class  ?
    Question 2 : Why can't Static Method be Abstract ?
    Question 3 : Can a Class be Abstract or Final Both, If yes, then why ?
    Thanks in Advance
    Saurabh Goel

    As per the above discussion two of your doubts have already been clarified  so I am taking only third one.
    A class cannot never be Abstract and final both coz Abstract signifies that the implementation of the class has not been defined completelyi.e. may be some methods have been defined but few methods are still missing implementation. 'Final' is used for those classes/methods which cannot be redefined  means the complete implementation of the method has been defined no one can implement further logic under the same method.
    If you are saying your method is Final then it cannot be overridden and Abstract implies that method implementation is yet to be defined which can only be implemented if that class/method is not 'Final'. So both the terms are contradictory.
    Hope it clarifies!!!
    Thanks,
    Vishesh

  • Static methods vs instant methods

    hi to all abap gurus
    thanks in advance
    all of the objects in the class can acess its its static attributes . and if u change the static attribute in an  object the change is visible in all other objects in the calsssss.
    can u pls expain this and tell the diffrence bewteen static and instance metod s?

    Hi,
    <b>Instance Method</b>
    You can declare instance methods by using the METHODS statement. They play a very important role as they can access all of the attributes of a class and can trigger all of the events of the class.
    <b>Static Methods</b>
    You can declare static methods by using the CLASS-METHODS statement. They are important and can only access static attributes and trigger static events.
    <b>STATIC METHODS</b>
    CAN ONLY USE STATIC COMPONENTS IN THEIR IMPLEMENTATION PART
    CAN BE CALLED USING THE CLASS
    Static methods (also referred to as class methods) are called using CALL METHOD <classname>=><class_method>.
    If you are calling a static method from within the class, you can omit the class name.
    You access static attributes using <classname>=><class_attribute>
    Regards,
    Padmam.

  • Redefine static method?

    It seems that I cannot redefine a static method in a subclass in ABAP OO, right?
    Is there a reason for that? Is this like this in other languages as well?

    That's true. You cannot redefine static methods in ABAP OO.
    I can add that a class that defines a public or protected static attribute shares this
    attribute with all its subclasses.
    Overriding static methods is possible for example in Java.
    This simple piece of code illustrates this:
    public class Super {
        public static String getNum(){
            return "I'm super";
         public static void main(String[] args) {
             System.out.println("Super: " + Super.getNum());
             System.out.println("Sub: " + Sub.getNum());
    public class Sub extends Super{
        public static String getNum(){
            return "I'm not";
    The output is:
    Super: I'm super
    Sub: I'm not
    When overriding methods in Java you must remember that an instance method cannot override a static method, and a static method cannot hide an instance method.
    In C# a static member can't be marked as 'override', 'virtual' or 'abstract'. But it it is possible to hide a base class static method in a sub-class by using the keyword 'new':
    public class Super
      public static void myMethod()
    public class Sub: Super
      public new static void myMethod()

Maybe you are looking for

  • 8300 Freeze and Crash While on Phone

    I've had my 8300 since February or so and for the last several months it's been doing this thing where I am talking to someone, when suddenly they get cut off.  The screen is usually black at this point (because I wasn't using it anyways) but the red

  • How can i use this as an applet ?

    i have this applet : import java.applet.*; import java.io.*; public class calculator2 extends Applet { /*<Applet code=calculator2.class width=500 height=500></applet>*/ /*the above comment has to be there for applet view to work. Type in at the promt

  • Need help in read statment

    Hi, i have a internal table with following records, BDZEI     PDATU     PLNMG 1083     20071029     4 <b>1083     20071029     44</b> 1096     20071029     44 1096     20071029     100 <b>1096     20071029     62</b> 1089     20071029     32 <b>1089 

  • Tables in JTextPane

    Hello dear Java Developers, i have one question about how to visualize an editable Table on a JTextPane. I Know i can input HTML-Code in a JTextPane and it can display all HTMl Components like Images and Tables, but i need generate a table without HT

  • Oracle7 ODBC Driver with an Oracle 8 database

    Does anybody know if there are any issues with using an Oracle 7 ODBC driver to access information on an Oracle 8 database?