HOW-TO initialize class variable

How can an annotation initialize a class variable? For example, JEE5 has an annotation called @EJB that initializes a class variable with a remote or local interface:
@Stateless class Foo
@EJB bar;
bar.scoobyDoobyDoo(); // I can use bar seemingly before it was initialized!
In general terms, how can annotation be used to initialize class variables?

It can't.
What it can do is tell something else that this needs to be done, and that something else can do it.
That something else might be an annotation processor running at build / compile time, which might generate some code to do it, or might generate some configuration file that causes it to be done later.
That something else might alternatively be a runtime artifact, that can look at the annotation and carry out the requested operation. For example a container could do it.
So an annotation cannot do anything, including initailizing a class variable, but it can declare that the class variable needs to be initialized in some way.
Bruce

Similar Messages

  • How to initialize a variable

    Hi,
    I'm trying to initialize a variable due to an error but I don't know how to do it.
    I have the following code:
    public class Multimedia
    String titulo;
    String autor;
    int duracion;
    Multimedia(String titulo, String autor, int duracion)
    this.titulo=titulo;
    this.autor=autor;
    this.duracion=duracion;
    }

    In class you have declared :
    Multimedia[] listamultimedia=new Multimedia[20];And in for loop you are using:
    listamultimedia=new Multimedia[20];First statement means : listamultimedia is an array of Multimedia with 20 elements.
    Second statement means :*Each element of listamultimedia* is an array of 20 elements. That would mean listamultimedia is array of array i.e 2-dimensional array.
    So you got the problem i guess. Its trivial to solve now.
    Edited by: J2EE_Life on Apr 8, 2012 5:04 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to access class variables in anonymous class??.

    I have a boolean class level variable. Fom a button action , this boolean will set to true and then it used in anonymous class. In anonymous class, I am getting default value instead of true. Could u anyone help in this plzzz.

    first of all, you don't want parent because that is something that Containers use to remember their containment hierarchy. you are thinking of super which is also incorrect, because that has to do with inheritance.
    the problem here is a scoping problem. you generally would use final if you were accessing variables in an anonymous class that are in the local scope. in this case, you just need to create some test code and play with it. snip the code below and play with it. it shows both the given examples and some additional ways to change/display class variables.
    good luck, hackerx
    import javax.swing.*;
    import java.awt.event.*;
    public class Foo extends JPanel
         private boolean the_b = true;
         public static void main(String[] args)
              Foo f = new Foo();
              JFrame frame = new JFrame();
              frame.getContentPane().add(f);
              frame.pack();
              frame.show();
         public Foo()
              // get your button
              JButton b = new JButton("Not!");
              b.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        // *** uncomment these to play around ***
                        // Foo.this.the_b = false; // this will work, but unnecessary
                        // the_b = false; // this works fine too
                        notFoo();
              this.add(b);
              // something to show the value that accesses a class variable
              // using an inner class instead of final nonsense
              DisplayThread t = new DisplayThread();
              t.start();
         private void notFoo()
              the_b = !the_b;
         class DisplayThread extends Thread
              public void run()
                   while(true)
                        System.err.println("boolean value: " + the_b);
                        try {
                        sleep(1000);
                        } catch(InterruptedException ie) {}
    }

  • How to declare class variable with generic parameters?

    I've got a class that declares a type parameter T. I know how to declare a static method, but this doesn't work for a static variable:
    public class Test< T >
        * Map of String to instances of T.
        * error: '(' expected (pointing to =)
        * <identifier> expected (pointing to () )
       private final static < T > Map< String, T > MAP = new HashMap< String, T >();
        * Get instance of type T associated with the given key.
       public final static < T > T getType( String key )
          return MAP.get( key );
    }Edited by: 845859 on Mar 20, 2011 11:46 AM

    jveritas wrote:
    I'm trying to create a generic polymorphic Factory class that contains boilerplate code.
    I don't want to have to rewrite the registration code every time I have a different return type and parameter.I haven't seen a case yet where that is reasonable.
    If you have hundreds of factories then something is wrong with your code, design and architecture.
    If you have a factory which requires large number of a varying input types (producing different types) then something is probably wrong with your code and design.
    A reasonable factory usage is one where you have say 20 classes to be created and you need to add a new class every 3 months. Along with additional functionality represented by the class itself and perhaps variances in usage. Thus adding about 3 lines of code to one class is trivial. Conversely if you have hundreds of classes to be created by the factory and you are adding them daily then it is likely that
    1. Something is wrong with the architecture which requires a new class every day.
    2. You should be using a dynamic mechanism for creation rather than static because you can't roll out a static update that often.
    More than that the idiom that leads to factory creation is different for each factory. A factory that creates a database connection is substantially different than the one used in dynamic rules logic processing. A generic version will not be suitable for both.
    Actualy the only case I know of where such a factory might be seem to be a 'good' idea is where someone has gotten it into their head that every class should be represented by an interface and every class created by a factory (its own factory.) And of course that is flawed.

  • How to initialize the variables in the subvi when the main vi running?

    Hi, friends!
    Now I am working on a project with labview. I make a main vi  including many subvis.
    When the main vi running, I want to reinnitialize the variables in the subvi to zero.
    I know that I can realize that  using the local variable when I enter the subvi,
    but I want to keep the the values when I left the subvi and saw them when I
    click in this subvi again. So, I do not reinitialize the subvi when it runs. But, I
    don not know how to reinitialize the indicators in the subvi when I run the main
    VI in the first instance. I try to use the global variables, but it seems do not work
    well. Would you like to give me some advice? Thanks a lot!

    Hi dec,
          If I understand your question, try using the "First Call?" node in your Sub-VI - to initialize values the first time the VI executes every time the top-level VI is Run.
    If this doesn't work for you, just post again!
    Cheers.
    "Inside every large program is a small program struggling to get out." (attributed to Tony Hoare)

  • How to keep class variables unaltered

    OK, I've read on how java passes variables around to and from functions, but I still have some questions.
    Tell me if my logic is right here.
    I made this little class for testing
    public class sah {
        private String[] test = {"This", " is ", "Java"};
        public void printstring() {
            System.out.println(test[0] + test[1] + test[2]);
        public String[] getarray() {
            return test;
    }then i ran it with this
    public class Main {
        public static void main(String[] args) {
            sah t = new sah();
            t.printstring();
            String[] a = t.getarray();
            a[1] = new String(" was ");
            t.printstring();
            return;
    }and of course the output was
    This is Java
    This was Javabut when i modify the sah class like this
    public class sah {
        private String[] test = {"This", " is ", "Java"};
        public void printstring() {
            System.out.println(test[0] + test[1] + test[2]);
        public String[] getarray() {
            String[] nTest = new String[3];
            for(int x = 0; x < 3; x++)
                nTest[x] = test[x];
            return nTest;
    }and run it, I get this
    This is Java
    This is Javathis time, because i just passed a copy of the reference of the strings as an array, it didn't have any effect on the original array and if i'm understanding the string class correctly, there is no way to modify the string once it has been created. All I can do is put a reference to another string in it's place, and not changing the orginal String[] in the sah class.
    So as long as i go through and make a copy of the String[] like I did the second time, there is no way that copy can be used to modify the original.
    And also, if that was an int[] the same would still hold true right, or is there something else I'm missing here?

    By the way,
    public String[] getarray() {
        String[] nTest = new String[3];
        for(int x = 0; x < 3; x++)
            nTest[x] = test[x];
        return nTest;
    }can be written as:
    public String[] getArray() {
        return nTest.clone();
    }

  • How to initialize array variable generated by Rosetta

    Hello,
    I have
    pl/sql types :
    TYPE xxg2c_pe is record (quota_name clob,revenue_class_name varchar2(30), performance_type varchar2(150),
    rate_table_name varchar2(80), formula_name varchar2(30),package_name varchar2(30) );
    TYPE xxg2c_pe_tab is table of xxg2c_pe;
    pl/sql procedure:
    PROCEDURE check_redundancy_pe(
    p_org_id IN cn_quotas_all.org_id%TYPE
                   ,p_comp_plan_id IN cn_quota_assigns_all.comp_plan_id%TYPE
    ,p_pe_tab OUT xxg2c_pe_tab
    ,x_return_status OUT varchar2
    ,x_msg_count OUT number
    ,x_msg_data OUT varchar2
    the signature generated by Rosetta:
    public static void checkRedundancyPe(
    OracleConnection _connection,
    BigDecimal p_org_id,
    BigDecimal p_comp_plan_id,
    Xxg2cPe [][] p_pe_tab,
    String [] x_return_status,
    BigDecimal [] x_msg_count,
    String [] x_msg_data
    ) throws SQLException :
    I call this method in java:
    xxg2cCompPlanUtilsPkg.checkRedundancyPe(
    conn,
    new BigDecimal(getOADBTransaction().getOrgId()),
    new BigDecimal(compPlanId),
    quotaTAB,
    returnStatus,
    msgCount,
    msgData);
    But before I call this method, I need to initialize quotaTAB as:
    Xxg2cCompPlanUtilsPkg.Xxg2cPe quotaTAB [][] = new Xxg2cCompPlanUtilsPkg.Xxg2cPe[size][6];
    Since quotaTAB is an output parameter, before I call the method, I don't know its size, so what size do I need to put for initialization?
    thanks for your help.
    Lei

    Hello,
    I have
    pl/sql types :
    TYPE xxg2c_pe is record (quota_name clob,revenue_class_name varchar2(30), performance_type varchar2(150),
    rate_table_name varchar2(80), formula_name varchar2(30),package_name varchar2(30) );
    TYPE xxg2c_pe_tab is table of xxg2c_pe;
    pl/sql procedure:
    PROCEDURE check_redundancy_pe(
    p_org_id IN cn_quotas_all.org_id%TYPE
    ,p_comp_plan_id IN cn_quota_assigns_all.comp_plan_id%TYPE
    ,p_pe_tab OUT xxg2c_pe_tab
    ,x_return_status OUT varchar2
    ,x_msg_count OUT number
    ,x_msg_data OUT varchar2
    the signature generated by Rosetta:
    public static void checkRedundancyPe(
    OracleConnection _connection,
    BigDecimal p_org_id,
    BigDecimal p_comp_plan_id,
    Xxg2cPe ][ p_pe_tab,
    String [] x_return_status,
    BigDecimal [] x_msg_count,
    String [] x_msg_data
    ) throws SQLException :
    I call this method in java:
    xxg2cCompPlanUtilsPkg.checkRedundancyPe(
    conn,
    new BigDecimal(getOADBTransaction().getOrgId()),
    new BigDecimal(compPlanId),
    quotaTAB,
    returnStatus,
    msgCount,
    msgData);
    But before I call this method, I need to initialize quotaTAB as:
    Xxg2cCompPlanUtilsPkg.Xxg2cPe quotaTAB [] [] = new Xxg2cCompPlanUtilsPkg.Xxg2cPe [size][6];
    Since quotaTAB is an output parameter, before I call the method, I don't know its size, so what size do I need to put for initialization?
    thanks for your help.
    Lei
    Edited by: user571830 on Feb 13, 2009 1:48 AM

  • How to initialize variable? (ArrayList String [])

    How to initialize this variable correctly, without getting a type safety warning?
    ArrayList<String>[] var = ?
    Thanks & Best regards,
    Kristian
    Message was edited by:
    Kriskra

    I need to use an array in this case... Thanks for
    your advice anyway...And the answer still is arrays and generics don't mix so your request is impossible without ignoring the warning.
    Try@SuppressWarnings("unchecked")
    ArrayList<String>[] var = new ArrayList[10];

  • Class variables don't exist at initialize() time?

    Excerpt of Slam.mxml (default package):
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                      xmlns:s="library://ns.adobe.com/flex/spark"
                      xmlns:mx="library://ns.adobe.com/flex/mx"
                      xmlns:components="components.*"
                      minWidth="955" minHeight="600" width="1000" height="720"
                      initialize="Initialize()"
                      creationPolicy="auto">
         <fx:Script>
              <![CDATA[
                   protected function Initialize():void
                        Global.app = this;
              ]]>
         </fx:Script>
    </s:Application>
    Excerpt of Global.mxml (default package):
    <?xml version="1.0" encoding="utf-8"?>
    <fx:Object xmlns:fx="http://ns.adobe.com/mxml/2009"
                 xmlns:s="library://ns.adobe.com/flex/spark"
                 xmlns:mx="library://ns.adobe.com/flex/mx">
         <fx:Script>
              <![CDATA[
                   public static var app:Slam = null;
              ]]>
         </fx:Script>
    </fx:Object>
    When I run the app I get an error in Initialize() because Global is null.  Global is a class name and Global.app is a class variable, a static.  How can they not exist at initialize time?  Suggestions for how to deal with this?  Thanks.

    No, running just these files doesn't exhibit the issue for me.  I'm using Flex 4.1.  However, I was able to come up with a minimal set of files that does show the problem.  Slam.mxml is the same as before.  Global.mxml becomes:
    <?xml version="1.0" encoding="utf-8"?>
    <fx:Object xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/mx">
         <fx:Script>
              <![CDATA[
                   public static var app:Slam = null;
                   public static const WIDGET_COLOR:uint = 0x987654;
                   public static var widgets:Widgets = new Widgets();
              ]]>
         </fx:Script>
    </fx:Object>
    and add an additional file, Widgets.as:
    package
         public class Widgets
             public function Widgets()
                  wColor = Global.WIDGET_COLOR;
             protected var wColor:int;
    This blows up with Global == null at the wColor initialization in Widgets.as.  I suspect there is some sort of chicken-and-egg issue going on here.  That Global isn't fully setup until it has initialized its widgets member, but initializing the widgets member needs Global fully setup.
    Moving the initialization of the widgets member to a separate Initialize function in Global, called from Slam.Initialize(), fixes the problem.

  • Class variable initialization

    I have noticed that class variable initialization occurs AFTER the constructor is called.
    Why is this, and is this intentional?
    It has caused strange behaviour in my SE java applications I am porting to MIDP.
    Thanks
    - Adam

    Hi,
    Error 1:
    The problem only arises if you use the unassigned variable:
    int i;
    int y = i; // Use of unassigned variable here
    you can just assign a value to i to solve this:
    int i = 0;
    int y = i; // Use of unassigned variable here
    Error 2 and 3 have to do with static and non-static, not with the initialization per se. This is how it works:
    static members (e.g. fields) can be accessed using this syntax: <Classname>.<FieldName>, e.g:
    public static class Helpers
    public static int SomeDataValue { get; set; }
    class Program
    static void Main(string[] args)
    Helpers.SomeDataValue = 22;
    On the other hand, non-static members are accessed like this: <instance>.<fieldname>. So you always need an instance of a class to access the field:
    public class Order
    public int OrderNumber { get; set; }
    class Program
    static void Main(string[] args)
    Order o = new Order();
    o.OrderNumber = 12;
    Rgds MM

  • How to access the parent class variable or object in java

    Hi Gurus,
    I encounter an issue when try to refer to parent class variable or object instance in java.
    The issue is when the child class reside in different location from the parent class as shown below.
    - ClassA and ClassB are reside in xxx.oracle.apps.inv.mo.server;
    - Derived is reside in xxx.oracle.apps.inv.mo.server.test;
    Let say ClassA and ClassB are the base / seeded class and can not be modified. How can i refer to the variable or object instance of ClassA and ClassB inside Derived class.
    package xxx.oracle.apps.inv.mo.server;
    public class ClassA {
        public int i=10;
    package xxx.oracle.apps.inv.mo.server;
    public class ClassB extends ClassA{
        int i=20;   
    package xxx.oracle.apps.inv.mo.server.test;
    import xxx.oracle.apps.inv.mo.server.ClassA;
    import xxx.oracle.apps.inv.mo.server.ClassB;
    public class Derived extends ClassB {
        int i=30;
        public Derived() {
           System.out.println(this.i);                  // this will print 30
           System.out.println(((ClassB)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassB
           System.out.println(((ClassA)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassA
        public static void main(String[] args) { 
            Derived d = new Derived(); 
    Many thanks in advance,
    Fendy

    Hi ,
    You cannot  access the controller attribute instead create an instance of the controller class and access the attribute in the set method
    OR create a static method X in the controller class and store the value in that method. and you can access the attribute by 
    Call method class=>X
    OR if the attribute is static you can access by classname=>attribute.
    Regards,
    Gangadhar.S
    Edited by: gangadhar rao on Mar 10, 2011 6:56 AM

  • How do we initialize DAL variables without making changes to INI files?

    We have an application which currently use only two DALs. We would like to add a DAL to popluate certain data on the form. We have encountered an issue with initialization of dal vairables.
    One of the solutionis that set FlushDalSymbo = Yes in the FSISYS file.
    However, this involves INI file change which we would like to avoid.
    So, is there a way to initialize dal variables, without making changes to INI files? If so, how?
    Thanks,
    Bala

    Hi Bala,
    Initializing a variable is simple, you just need to set the value to blank or zero:
    Variable = ""
    #Variable =0
    $Variable = 0.00
    You can place the declaration at the beginning of your script, of course replacing "Variable" with the actual name of you variable.
    Gaétan

  • How to access an element using its name or id if it is not a class variable?

    I am trying to retrieve the element I added to my UI in a different  function. I am using actionscript 3. I know I can put the variable into a  class variable, so it can be access anywhere in the class, but I have  too many elements. Is there anyway I could access them without putting  them into class variable?
    Thanks.
    public class Test extends SkinnableContainer{
    // private var image:Image; <-- I try not to do this, too messy
    private function func1() {
        var image:Image = new Image();
        addElement(image);
    private function func2() {
        var image:Image = /* how to get the element from my UI without putting into class variable */

    Here is what works for me:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx"
                   creationComplete="init()"
                   minWidth="955" minHeight="600">
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                import spark.components.Image;
                private var  image:Image;
                private function init():void
                    image = new Image();
                    addElement(image);
                    trace(this["image"]);
            ]]>
        </fx:Script>   
    </s:Application>

  • Class Variable Instantiation: When and How

    I have a couple nitpicky questions. In the following class:
    1- Is it better to have a class variable initialized to a parent class of what it will eventually be instantiated?
    2- Is it better, knowing you'll instantiate that variable no matter what, to hold off and save the instantiation for later (like in the constructors)?
    public class ClassWithArrayList{
       List<String> list;
       public ClassWithArrayList(){
          list = new ArrayList<String>();
       public ClassWithArrayList(String arg){
          list = new ArrayList<String>();
    }I keep coming across code like this, and it seems a bit strange to me. Why not simply do:
    public class ClassWithArrayList{
       ArrayList<String> list = new ArrayList<String>();
       public ClassWithArrayList(){
       public ClassWithArrayList(String arg){
    }Is this simply a matter of style, or are there real benefits to coding the first way?

    kevinaworkman wrote:
    BigDaddyLoveHandles wrote:
    kevinaworkman wrote:
    Isn't it "better" to give all variables the most specific type that works?No.Is it worse?Depends.
    >
    BigDaddyLoveHandles wrote:
    kevinaworkman wrote:
    To be extreme, why not just start everything off as an Object? That "doesn't work".Yes yes, that's a bad example. But I still don't understand the motive to stay as general as possible. Is it just a personal preference, or is there a real reason behind it?
    BigDaddyLoveHandles wrote:
    kevinaworkman wrote:
    But what are the benefits of being more general instead of specific? Simplicity, clarity.Isn't it more clear to say "I want this to be an ArrayList<String>" as opposed to "I want this to be any kind of List<String>"?Since when is revealing your implementation details considered clarity? I don't want to know that stuff. It just muddies the waters.
    >
    BigDaddyLoveHandles wrote:
    kevinaworkman wrote:
    It seems to me that being as specific as possible would make for clearer code?It seems to be the opposite to me.Maybe we are just arguing personal preference, in which case it doesn't matter.
    BigDaddyLoveHandles wrote:
    Think about a return type:
    List<String> getStuff()
    //versus
    ArrayList<String> getStuff()Which is simpler? Which locks you into one particular implementation?I still prefer the ArrayList version. It definitely seems simpler to me, and I don't see it as locking me into a particular implementation. Instead, I see it as being more accurate about what I should expect to be working with.What it you want to use a LinkedList instead or return the list returned by Collections.synchronizedList or unmodifiableList? This is the dictionary definition of "locking me into a particular implementation".
    You need to learn to love abstraction. "More accurate" should not mean spilling the beans about arbitrary implementation choices.
    It seems like maybe this is a personal preference and not a right vs wrong kind of code decision?In a small example it may make no difference. But in general, one should strive for the right level of abstraction.

  • Assign a value to class variable

    I want to define a class variable in class. And I want all subclasses of that class ot have a different value for that class variable. How can I do that?
    public class BaseClass {
      public static String tableName = "";
    }Now if I have a ClassA and I want to assign a value like this :
    public class ClassA extends BaseClass {
      tableName = "location";
    } I got an error message.
    I can move it in a static initializer block but then it will only work when the class is loaded. In my case its possible i want to get this value without loading the class.
    Ditto if i move it to constructor.
    Any input? Thanks

    Are you saying that if i have 2 classes ClassA and
    ClassB inherited from BaseClass, then both are
    sharing the same copy of 'tableName' staticvariable?
    If yes then I should go with an instance variable.No, I am saying that you can easily declare a
    tablName in A and another tableName in B.
    A.tableName will be shared between all the instances
    s of A. B.tableName will be shared between all the
    instances of B. And BaseClass.tableName is
    irelevant. I think you try to use
    BaseClass.tableName as some kind of template for
    sub-classes, but this does not happen: you need to
    declare tableName again and again in each subclass.
    IThanks for clarifying. Each class needs to have a variable "tableName" and it needs to have one copy of this variable for all of that class's objects. 2 classes will not have the same value of this tableName variable.
    Thats why I was defining it as static variable. And I define it in BaseClass so that I dont have to define it again in each subclass.
    Is there any better way? Thanks

Maybe you are looking for