Generics in static fields

Hi, I am trying to make a class which has some generic fields. I understand that it would not work just like that as the compiler has no way what the generic fields should actually be in a static context.
I want to use the generic class as an abstract class which would be extended, so that way the generics should be resolvable. Is there any way to make this work this way or should I not use generics and go type unsafe?
This is what I want to do in code:
abstract class ClassToBeExtended<A>
     static A a;
class UsingTheOther extends ClassToBeExtended<String> {}

It is supposed to be a class that adds relations between other classes:
// Simplified
class RelationBetweenAandB extends TheClass<A, B> {}
class SomeOtherClass
  void foo()
    A a = new A();
    B b1 = new B();
    B b2 = new B();
    RelationBetweenAandB.add(a, b1);
    RelationBetweenAandB.add(a, b2);
    new YetAnotherClass().listRelationsOf(a);
class YetAnotherClass
  public void listRelationsOf(A a)
      for (B b : RelationBetweenAandB.allRhs(a))
      ; // Iterate through b1 and b2
}Having static fields will make the relation useful from anywhere in the application, if it is not static then all the objects that are going to be used in a relation have to instantiate the class which wlll probably introduce a lot of overhead.
abstract class SomeClass<A extends OtherClass>
  static OtherClass a;
} Would require me to have Object in stead of OtherClass because I want all types of object to be in a relation, which is what I meant by going type unsafe :)
Message was edited by:
SavageNLD
Added some more reasoning about why I want static fields

Similar Messages

  • Different behaviour reading static field Windows vs Linux

    I have a class B that is a subclass of class A. Class A has a protected static field. In windows, reading this field from a static method of class B yields the desired results, meaning that the field has the value updated somewhere else. Running the same code in Linux, the field contains the value assigned to it at declaration time:
    It goes like this:
    package packageA;
    public class A
    protected static Collection items = new ArrayList();
    public static void addItem(Object item)
    items.add(item);
    } // class A
    package packageB;
    public class B
    extends A
    public static void methodA()
    System.out.println(A.modules.size());
    System.out.println(B.modules.getSize());
    System.out.println(modules.size());
    } // class B
    import packageA.A;
    import packageB.B;
    public static void void main(String[] args)
    Object item;
    item = new String("");
    A.addItem(item);
    B.method();
    } // main(String[])
    What is even more strange, is that if I run the above example in a new project, the results are as expected. But if I run this other project I am working on, the results are as if B.items is independent of A.items. Even if I implement a method A.getItems() and call it from B.method() to store the items in a variable local to B.method(), the result is an empty ArrayList.
    My first attempt was to place the A and B classes in the same package, and since the results were as expected, I changed each class to its own package and the Main class to an independent package. The results do not change in this scenario.
    Your help is appreciated.
    The environment is:
    Netbeans 5.5
    JRE 1.6.0-b105
    xubuntu (Linux 2.6.20-16-generic i686 GNU/Linux(
    Juan Carlos

    I have just noticed that the "odd" behaviour does not happen everywhere (but it does happen everytime).
    I realized that there is another part of code that references the same static field and the value in that case is the correct one.
    Also, while debugging under Netbeans (on the line of code that gives the unexpected value), the "tip" that is displayed when the cursor is placed over the name of the field, the value is correct.
    So I decided to check the Call Stack and noticed some Hidden Source Calls. They are hidden because of a call to LoginContext.login() Furthermore, that call results in a call to AccessController.doPrivileged()
    Could that be the problem? If so, how do I solve it. At this point I am lost here, I don't have an idea of where to go now.
    Thanks.
    JC

  • How can I share a static field between 2 class loaders?

    Hi,
    I've been googling for 2 days and it now seems I'm not understanding something because nobody seems to have my problem. Please, somebody tell me if I'm crazy.
    The system's architecture:
    I've got a web application running in a SunOne server. The app uses Struts for the MVC part and Spring to deal with business services and DAOs.
    Beside the web app, beyond the application context, but in the same physical server, there are some processes, kind of batch processes that update tables and that kind of stuff, that run once a day. Theese processes are plain Java classes, with a main method, that are executed from ".sh" scripts with the "java" command.
    What do I need to do?
    "Simple". I need one of those Java processes to use one of the web app's service. This service has some DAOs injected by Spring. And the service itself is a bean defined in the Spring configuration file.
    The solution is made-up of 2 parts:
    1. I created a class, in the web app, with a static method that returns any bean defined in the Spring configuration file, or in other words, any bean in the application context. In my case, this method returns the service I need.
    public class SpringApplicationContext implements ApplicationContextAware {
         private static ApplicationContext appContext;
         public void setApplicationContext(ApplicationContext context) throws BeansException {
              appContext = context;
         public static Object getBean(String nombreBean) {
              return appContext.getBean(nombreBean);
    }The ApplicationContext is injected to the class by Spring through the setApplicationContext method. This is set in the Spring configuration file.
    Well, this works fine if I call the getBean method from any class in the web app. But that's not what I need. I need to get a bean from outside the web app. From the "Java batch process".
    2. Why doesn't it work from outside the web app? Because when I call getBean from the process outside the web app, a different class loader is executed to load the SpringApplicationContext class. Thus, the static field appContext is null. Am I right?
    So, the question I need you to please answer me, the question I didn't find in Google:
    How can I share the static field between the 2 class loaders?
    If I can't, how can I load the SpringApplicationContext class, from the "Java batch process", with the same class loader my web app was started?
    Or, do I need to load the SpringApplicationContext class again? Can't I use, from the process, the class already loaded by my web app?
    I' sorry about my so extensive post...
    Thank you very much!

    zibilico wrote:
    But maybe, if the web service stuff gets to complicated or it doesn't fulfill my needs, I'll set up a separate Spring context, that gets loaded everytime I run the "Java batch process". It'll have it's own Spring configuration files (these will be a fragment of the web app's config files), where I'll define only the beans I need to use, say the service and the 2 DAOs, and also the DB connection. Additionally, I'll set the classpath to use the beans classes of the web app. Thus, if the service and DAOs were modified in the app server, the process would load the modified classes in the following execution.You'll almost certainly have to do that even if you do use RMI, Web services etc. to connect.
    What I suggest is that you split your web project into two source trees, the stuff that relates strictly to the web front end and the code which will be shared with the batch. The latter can then be treated as a library used by both the batch and web projects. That can include splitting Spring configuration files into common and specific, the common beans file can be retrieved from the classpath with an include. I regularly split web projects this way anyway, it helps impose decoupling between View/Controller and Model layers.
    On the other hand, you might consider running these batch processes inside the web server on background threads.

  • Is read-only access to a static field correct without volatile/locking?

    Hello,
    I wonder wether the following code is safe:
    static UnicomServerCentral instance;
         public static void setInstance(UnicomServerCentral central)
              synchronized (UnicomServerCentral.class)
                   instance = central;
         public static UnicomServerCentral getInstance()
              UnicomServerCentral central = thisinstance;
              if (central == null)
                   synchronized (UnicomServerCentral.class)
                        central = this.instance;
              return central;
         }The static field instance is already guaranteed to be set. Is this safe?
    Thank you in advance, lg Clemens

    It might be safe in a particular context if there is
    additional synchronization involving the construction
    of the the "central" object and the execution of any
    threads that might call getInstance.Well if getInstance() returns null I simply spin as long as I get a non-null value back - so the only circumstance I could get here null is initialization.
    Since this example is a perfect does-not-work-dcl example I'll search the net for exmplanations.
    Thanks a lot, lg Clemens

  • Adobe Reader files missing information in static fields after being emailed?

    Hello, I have emailed the same person three seperate times with an attached PDF file that does have some fillable fields and some static fields. One time I email them the file, and the data in the static fields has been changed, but the fillable fields are the same, so I emailed it again and this time all the fields are completely blank, any ideas?

    Email transmissions can do all kinds of things, including attachments getting damaged or lost.  Far better and safer is to use a file sharing service like Acrobat.com, Dropbox, Google Drive, ..., then send the link by email.

  • The static field should be accessed in a static way

    Hello,
    I am developing a java app in eclipse and I am getting the error message:
    The static field Calendar.DAY_OF_WEEK should be accessed in a static way
    I am trying to get the first day of the first week in the current month, here is my code:
    GregorianCalendar firstDayOfThisMonthCalendar = new GregorianCalendar(Calendar.YEAR, Calendar.MONTH, 1);
    int firstDayOfThisMonth = firstDayOfThisMonthCalendar.DAY_OF_WEEK;I though the problem was that I'm supposed to write the code like this:
    firstDayOfThisMonthCalendar.get(Calendar.DAY_OF_WEEK); but then I get the wrong value back

    That's what I critice about u people, always ready to
    complain, It's not complaining. It's pointing out problems with your code. You should thank him.
    but do u put the code in here the way that
    someone could read it ? Easy to say 'use
    simpleDateFormat. Oh, careful, January returns 0, not
    1'.Using SimpleDateFormat is an easier and more correct way to do it. Trying to use the numerical value of the month constants is incorrect coding. You should thank him for educating you.
    Why can't u write the code in here so there's no
    chance that somebody will ask again.Such code is not possible. No matter what code you write, somebody can misunderstand it.
    If you write the code correctly--using SimpleDateFormat--then the code will be correct (which is the most important criteria) and clear (which is important, but not as important as correctness).
    But if you prefer to think that your way is always perfect and are afraid to admit your mistakes and learn from them, that's your prerogative.

  • Static field should be accessed in a static way

    I am getting the following warning message: static field should be accessed in a static way. What does it mean?
    thanks.

    Below is the code. I'm getting the "warning" in the Waiter class on the statement: this.r = r;
    public class Threads {
         public Threads() {
              super();
              System.out.println("==> Threads.constructor");
         public static void main(String args[]){
              System.out.println("==> main");
              Threads t = new Threads();
              Rendezvous r = new Rendezvous();
              Waiter w1 = new Waiter(r);w1.start();
              Waiter w2 = new Waiter(r);w2.start();
              Waiter w3 = new Waiter(r);w3.start();
              new Waiter(r).start();
              new Waiter(r).start();
              new Waiter(r).start();
              new Waiter(r).start();
              Waiter w4 = new Waiter(r);w4.start();
              Waiter w5 = new Waiter(r);w5.start();
              Waiter w6 = new Waiter(r);w6.start();
              System.out.println("==> main done");
         static class Rendezvous{
              private static int ri = -1;
              public synchronized void doWait(Waiter w){  
                   System.out.println("==> doWait - sNum="+w.serialNum+",tries="+w.numTries+" name="+Thread.currentThread().getName());
                   while (w.numTries < 5){
                        notifyAll();
                        w.numTries++;
                        System.out.println("==> before wait()- sNum="+w.serialNum+",tries="+w.numTries);
                        try {wait();} catch (InterruptedException e){}
                        System.out.println("==> after wait() - sNum="+w.serialNum+",tries="+w.numTries);
                   } //end-while
              } //end-doWait()
              public void doNotify(){
                   notify();
         } //end-Rendezvous-class
         static class Waiter extends Thread{
              private static int counter = 1000;
              private static Rendezvous r;
              public int serialNum;
              public int numTries = 0;
              public Waiter(Rendezvous r){
                   this.r = r;
                   serialNum = counter++;
                   System.out.println("==> Waiter.counstructor:sNnum="+serialNum+" name="+Thread.currentThread().getName());
              public void run(){
                   System.out.println("==> Waiter.run():" + serialNum+" name="+Thread.currentThread().getName());
                   r.doWait(this);

  • Static field changes for both instances

    Whenever I construct a new object with a static field or use a set method on any of the instances of that object, the static field will change to the last modification made. In the case of my program, whenever the static String color field is changed to the last modification made. This only happens with the static fields, the other fields work just fine.
    Why does this problem occur?

    Sorry, I can't understand the question. If you have lots of different objects, all of the same class, they all share one copy of the static field, so if you invoke a method that changes the static field on one instance, all the other instances will see that change.
    if you don't want this behaviour, don't make the field static; then each instance will have its own copy of the field.

  • Static fields in serialized Vector objects

    just a curious question:
    If I have a Vector filled with Objects of all the same type, and the Object contains a static field, and I then Serialize the Vector, will it still give better performance than if the field wasn't static? Thanks,
    Max

    nevermind - found out the hard way that static fields won't get Serialized

  • Using Objects to Initialize Static Fields: Good or Bad

    I have a Command interface and a bunch of Commands that implement it (i.e. CmdJoin,CmdQuit). These Commands' settings change at runtime (i.e. required access levels, String identifiers). I don't want to have to store an instance of each Command in a database to save their settings , so instead I'm using the obvious solution: making static fields in these commands for these settings. This way, I can use a Simple Factory to return a Command, change its settings, execute it, and forget it, and still have the settings for that Command apply to all Commands. Yet I want to be able to modify and access fields of different Commands polymorphically. How can I have these commands' settings-related fields be static while modifying and accessing these fields polymorphically?
    Here's what I have though of. First of all, interfaces can't have static methods. Secondly, neither can abstract classes. I also can't extend a base class which implements these settings-related fields and their interface, because then the fields would belong to all child classes of this base class, whereas I just want it to belong to a certain child class of the base class (i.e. all instances of CmdJoin or CmdQuit).
    I've thought of two solutions.
    The first is implementing a concrete interface in an abstract base class (getting rid of the Command interface) and overriding it in child classes, so that I can use the interface of the base class and the fields of the child classes.
    The second is having no base class, and just a bunch of Commands implementing the interface with their own static fields. I would initialize these fields by passing arguments to their constructors.
    These solutions seem very sloppy though! Are there any better ways?

    To clarify, I want all objects of type A to be able to respond to a static method declared in type A yet still remember their implementation of this static method. I provided two solutions that I have thought of, and I find them sloppy, so I'm asking if there's a better way.

  • Static field and subclasses

    If a parent class with a private static field has 5 subclasses, each with a private static field of the same name as the parent field and the parent has an accessor method for this field, will each of the 5 subclasses return its own version of the field if the accessor method is called (from the children of course)? The method is not overridden in the subclasses.

    Did you try it and see what would happen?

  • Static field component in virtual machine spec

    Hello.
    I can&#8217;t understand some point in JavaCard Virtual Machine Specification v2.2.2.
    Section: 6.10 Static Field Component. See table 6-14. segment 4 &#8211; it describe &#8220;primitive types initialized to non-default values&#8221;. It is describes by two parameters : non_default_value_count, non_default_values[].non_default_values &#8211; is image of all static primitive fields independence of it type &#8211; byte, short, int. This image consist from data in big-endian order.
    How I can use it at architecture with little-endian order?
    I can&#8217;t parse where short or int &#8211; I can&#8217;t convert it. How I can do it?

    As you pointed out it is not known from the CAP file format where single short or int values begin. At access time you know where the value starts and of which type it is. Therefore it looks like you have no choice but to convert the value at every access from or to big endian.
    This is from a design perspective definitely not nice regarding the VM design but I don't think the performance penalty is too costly.

  • StreamTokenizer static fields

    Maybe this is a stupid question but why does this compile without problems:
    Reader r = new BufferedReader(new InputStreamReader(System.in));
    StreamTokenizer tok = new StreamTokenizer(r);
              // StreamTokenizer tok = new StreamTokenizer(System.in);
              try{
                   while (tok.nextToken() != StreamTokenizer.TT_EOF){
                        switch (tok.ttype) {        // ttype is token type
                             case StreamTokenizer.TT_NUMBER: 
                                  System.out.println("number " + tok.nval);
                                  break;
         ....But this:
    Reader r = new BufferedReader(new InputStreamReader(System.in));
    StreamTokenizer tok = new StreamTokenizer(r);
              // StreamTokenizer tok = new StreamTokenizer(System.in);
              try{
                   while (tok.nextToken() != StreamTokenizer.TT_EOF){
                        switch (tok.ttype) {        
                             case tok.TT_NUMBER:  // nval is numeric value
                                  System.out.println("number " + tok.nval);
                                  break;
         ....                    gives the following compiling error:
    constant expression required
        case tok.TT_NUMBER:  value
               ^
    1 errorI thought static fields can be access both through the name of the class and objects of it.
    The version that doesn't compile comes from a book which makes it slightly more confusing.

    excuse my wording. I have been using >= mostly, though
    I do know that > exists. If I replace the >
    with >= and compile there are no errors. But I also
    get the following errors with the >
    # javac TestLight.java
    TestLight.java:13: ')' expected
    if (a.KWH_PRICE > 0)
    ^
    TestLight.java:13: not a statement
    if (a.KWH_PRICE > 0)
    ^
    TestLight.java:13: ';' expected
    if (a.KWH_PRICE > 0)
    ^
    TestLight.java:13: cannot resolve symbol
    symbol : variable gt
    location: class TestLight
    if (a.KWH_PRICE > 0)
    ^
    4 errorsYou really get errors then ?
    Very strange, I don't get any.....

  • Avoid assigning to servlet static fields without using a shared lock??

    Hi
    i received the following warning on my code, does anyone give me a help on this? Thanks
    "Avoid assigning to servlet static fields from javax.servlet.Service.service () without using a shared lock."
    And my code are as follow:
    public class MyDataSource {
        private static DataSource ds = null;
        public static DataSource getDataSource() throws NamingException, Exception
            if (ds==null){
                   InitialContext ctx = new InitialContext();
                try{
                    synchronized(getDataSource()){
                    if(ds==null){
                        ds = (DataSource) ctx.lookup(SysProperties.ds);
                } catch (Exception ex) {
                    throw new Exception("DBConnection Exception: " +ex.toString());
                }finally{
                        if(ctx !=null){
                            ctx.close();
            return ds;       
    }

    The service method of a servlet is multi-threaded to handle multiple requests. Hence,any static or public fields accessed by the service method should be restricted to a single thread access (for example using synchronized keyword) to make it thread-safe. That is why you are getting the warning message.

  • Static fields storage area

    Hi,
    local variables are stored on the stack which is private to each thread, all classes instaces are stored on the heap which is shared amongst all threads,
    so where are static class variables stored? they're not instances and they are shared amongst all threads....

    In older versions of the JVM the memory areas could be divided, Method Area and the heap. In the new implementations however there is no such segregation.vm spec, section 3.5.4 supports exactly what you said:
    Although the method area is logically part of the heap, simple implementations may choose not to either garbage collect or compact it.
    yet I can't find a clear explanation in there regarding static fields storage....
    I guess it doesn't really matter, since the destinction between the method area and the heap is not mandated by the spec...

Maybe you are looking for

  • My apple tv my picture has disappeared!

    My apple tv is all working but i get no picture.  I've checked all the cables etc, performed a reset but still nothing.  It was working then it just stopped.  Does anybody have any ideas apart from taking it back to the retailer?

  • Troubles Importing Songs Onto Zen Mi

    When I go into my MediaOrganizer, it recognizes that my Zen Micro 5GB is connected. OK so now I click that and it is in folders now, and it never was before. Before being that I had to uninstall all my Creative stuff and all the drivers and re-instal

  • Parallel Execution Of Procedures

    Hi All, I have 4 procedures proc1,proc2,proc3 and proc4.I have to execute the procedures like below Proc1 will be executed first and after the execution of the proc1, it will trigger proc2 and proc3 to execute in parallel, if the execution of both th

  • R12 on Dell servers ???

    Hi, How is Oracle apps R12 on dell servers with EMC storage? Till now I have always used hp or sun servers. On my new they are thinking of R12 upgrade with Dell servers? Any input is apreciated.

  • Can not forword SAF topic to a managed server

    I configured SAF topics on A-server, B-server, C-server, D-server, E-server and let those SAF topics to forword to F-server with 'store and forword agent'function. There are much SAF topics to forword. Now, I got below exception: ####<2010-07-02T17:3