Using static methods in JavaBeans
Hi:
I am creating several beans as part of my application. Is it ok, to make all of them static (no global variables are used) and access in JSP's and Servlets as XXBean.method(var1, var 1). Is this a problem ? (vs creating a new XXBean and using it in every page/servlet).
I have gut feeling that static methods are better and give better memory usage and performance - as oppose in other scenario I am creating a new Bean for every page access - could not verify. and not sure not creating (new Bean) would give any problems.
Thanks for sharing.
I think you mixed up JavaBeans and Enterprise JavaBeans (EJBs) ...
I think Sun Microsystems really named them badly ...
They are in fact totally different things ...
I agree with them.
Please read the tutorials first.
Asuka Kenji (UserID = 289)
(Duke Dollar Hunting now ...)
Similar Messages
-
Why not to use static methods - with example
Hi Everyone,
I'd like to continue the below thread about "why not to use static methods"
Why not to use static methods
with a concrete example.
In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
I created the following class for these "operations" with static methods:
public class KeyboardInput {
private static Robot r;
static {
try {
r = new Robot();
} catch (AWTException e) {
throw new RuntimeException(e + "Robot couldn't be initialized.");
public static void wait(int millis){
r.delay(millis);
public static void copy() {
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_CONTROL);
public static void altTab() {
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_ALT);
// more methods like paste(), tab(), shiftTab(), rightArrow()
}Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
Thanks for any comments in advance,
lemonbostonmaheshguruswamy wrote:
lemonboston wrote:
maheshguruswamy wrote:
I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
If you use a Singleton (and and interface), you can do something like this:
KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class. -
GUI component services: Use static methods or query direct parent?
Hi
I have a large panel (covers most of the window) that contains a square grid of smaller panels. Each smaller panel contains a square grid of buttons. For instance, PnlGrid contains a few PnlGridSections and each PnlGridSection contains some BtnGrids.
There is certain funtionality that must be available to BtnGrid objects but I am not sure if I should simply provide static methods in PnlGrid and access them from everywhere else in the code or have BtnGrid ask its direct parent (i.e. PnlGridSection) to deal with it.
For instance, I am currently using a static method, PnlGrid.getIconCache(), to retrieve a reference to the icon cache and locate the texture I need from within a BtnGrid. Would it more correct to retrieve a pointer to the direct parent of this button (i.e. PnlGridSection) and have him return the pointer to the icon cache?
ThanksHi
I have a large panel (covers most of the window) that contains a square grid of smaller panels. Each smaller panel contains a square grid of buttons. For instance, PnlGrid contains a few PnlGridSections and each PnlGridSection contains some BtnGrids.
There is certain funtionality that must be available to BtnGrid objects but I am not sure if I should simply provide static methods in PnlGrid and access them from everywhere else in the code or have BtnGrid ask its direct parent (i.e. PnlGridSection) to deal with it.
For instance, I am currently using a static method, PnlGrid.getIconCache(), to retrieve a reference to the icon cache and locate the texture I need from within a BtnGrid. Would it more correct to retrieve a pointer to the direct parent of this button (i.e. PnlGridSection) and have him return the pointer to the icon cache?
Thanks -
NEED HELP WITH USING STATIC METHOD - PLEASE RESPOND ASAP!
I am trying to set a value on a class using a static method. I have defined a servlet attribute (let's call it myAttribute) on my webserver. I have a serlvet (let's call it myServlet) that has an init() method. I have modified this init() method to retrieve the attribute value (myAttribute). I need to make this attribute value accessible in another class (let's call it myOtherClass), so my question revolves around not knowing how to set this attribute value on my other class using a static method (let's call it setMyStuff()). I want to be able to make a call to the static method setMyStuff() with the value of my servlet attribute. I dont know enough about static member variables and methods. I need to know what to do in my init() method. I need to know what else I need to do in myServlet and also what all I need in the other class as well. I feel like a lot of my problems revolve around not knowing the proper syntax as well.
Please reply soon!!! Thanks in advance.class a
private static String aa = "";
public static setVar (String var)
aa = var;
class b
public void init()
a.aa = "try";
public static void main(String b[])
b myB = new b ();
b.init();
hope this help;
bye _drag -
Using static methods to instantiate an object
Hi,
I have a class A which has a static method which instantiates it. If I were to instantiate the class A twice with it's static method within class B then you would think class B would have two instances of class A, right?
Example:
class A
static int i = 0;
public A(int _i)
i = _i;
public static A newA(int _i)
return new A(_i);
class B
public B()
A.newA(5);
A.newA(3);
System.out.println(A.i);
public static void main(String[] args)
B b = new B();
}Is there really two instances of class A or just one? I think it would be the same one because if you check the int i it would be 3 and not 5. Maybe static instantiated objects have the same reference within the JVM as long as you don't reference them yourself?
-BruceIt
seems like you are the only one having trouble
understanding the question.Well I was only trying to help. If you don't want any help, its up to you, but if that's the case then I fail to see why you bothered posting in the first place...?
Allow me to point out the confusing points in your posts:
you would think class B would have two
instances of class A, right?The above makes no sense. What do you mean by one class "having" instances of another class? Perhaps you mean that class B holds two static references to instances of Class A, but in your code that is not the case. Can you explain what you mean by this?
Is there really two instances of class
A or just one?You have created two instances.
>I think it would be the same one because if you
check the int i it would be 3 and not 5.
I fail to see what that has to do with the number of instances that have been created...?
Maybe static instantiated objects have the
same reference within the JVM as long as you
don't reference them yourself????? What is a "static instantiated object"? If you mean that it was created via some call to a static method, then how is it different to creating an object inside the main method, or any other method that was called by main? (i.e. any method)
What do you mean by "the same reference within the JVM"? The same as what?
What happened to the first call "A.newA(5)"?
I think it was overidden by the second call
"A.newA(3)".As i already asked, what do you mean by this?
If you change the line for the constructor
in A to i = i * i you will get "9" as the
output, if you delete the call "A.newA(3)"
you will get "25" as the output. Yes. What part of this is cauing a problem? -
Best practice for using static methods
When i want to call a static method, should i call:
1) classInstance.staticMethod()
or should i call
2) ClassName.staticMethod()??
is the first style bad programming practice?dubwai: which compiler?I had assumed that this was what the JLS specifies, but intsead, it goes into length how to make the runtime environment treat calls to static methods on instances as if they were static calls on the variable's type.
However, I imagine anyone creating a compiler would go ahead and compile calls to static methods on instances to static calls on the variable's type instead of going through the effort of making the runtime environment treat calls to static methods on instances as if they were static calls on the variable's type.
But of course, it is concievable that somone didn't in their compiler. I doubt it but it is possible. Sun does compile calls to static methods on instances to static calls on the variable's type:
public class Garbage
public static void main(String[] args)
Garbage g = null;
method();
g.method();
public static void method()
System.out.println("method");
public class playground.Garbage extends java.lang.Object {
public playground.Garbage();
public static void main(java.lang.String[]);
public static void method();
Method playground.Garbage()
0 aload_0
1 invokespecial #1 <Method java.lang.Object()>
4 return
Method void main(java.lang.String[])
0 aconst_null
1 astore_1
2 invokestatic #3 <Method void method()>
5 invokestatic #3 <Method void method()>
8 return
Method void method()
0 getstatic #4 <Field java.io.PrintStream out>
3 ldc #5 <String "method">
5 invokevirtual #6 <Method void println(java.lang.String)>
8 return -
Why not to use static methods in interfaces?
why?
Because static methods are always attached to a particular class -- not an object. So object polymorphism (which is what interfaces are good for) won't help. Now, what you can do is say that subclasses must implement a method that looks an awful lot like a static method, in that it doesn't depend on object state.
This bugged me, and it still bugs me a little bit in that I have to instantiate an object of a type in order to call these pseudo-static methods. When the pseudo-static methods tell the user how to initialize the object, you get a bit of a chicken-and-egg problem. -
Virtual ESA appliance update and upgrade using static method
What are the static servers for updates and upgrading if you are using a virtual appliance ?
I know that the if you use a standard appliance they are:
downloads-static.ironport.com: 208.90.58.105 on port 80
update-manifests.ironport.com: 208.90.58.5 on port 443
updates-static.ironport.com: 208.90.58.25 on port 80
But I see that my virtual appliance is trying to go to "update-manifests.sco.cisco.com" - are there other differences for the virtual appliance ?Yes, I can confirm through my own experiences over the past week that the Virtual Appliances do not use the same update servers.
Virtual Appliances point to dynamichost update-manifests.sco.cisco.com - 208.90.58.6. I'm not sure about the static update IPs, as the static sub domains do not seem to exist on the sco.cisco.com and it looks like Cisco is using Akamai CDN to distribute updates over port 80. You may need to allow iyour Virtual ESAs out on port 80 any, and 443 seems to be a single host.
Also I found the following article most helpful for Virtual ESA Updates:
http://www.cisco.com/c/en/us/support/docs/security/email-security-appliance/118065-maintainandoperate-esa-00.html -
Hi,
I have few class variables like socket, and boolean datatypes in a class.
This class is intantiated in lot of place and everytime the new instance is created the variables are re-initialized to their original values.
I dont want variables values to change everytime an instance is created. So should i declare them static? if i do so is there any precaution or cautions i should look out for?
Thank you.Thank for the reply here is the code.
public class ServerComm{
//class variables.
private boolean connValid = false;
private Socket cvwSock;
//Open the connection to the CVW server.
public void openConnection() {
try {
cvwSock = new Socket(InetAddress.getByName(host), iport);
boolean isConnect = cvwSock.isConnected();
System.out.println("ServerComm,openconnection2:got socket conn: "
+ cvwSock);
connValid = true;
catch (Exception v) {
connValid = false;
System.out
.println("servercomm,openconnection3:You are trying to connect to CVW server with name: "
+ host + " Unknown CVW Server");
else
v.printStackTrace();
System.exit(1);
return;
* Sends a command to the CVW server if the connection is valid.
public void sendCmdToServer(String cmd) {
//connection valid become false with new instance of class so returns
if (!connValid)
return;
if (idleState) {
idleState = false;
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
ps.println(cmd);
ps.flush();
// opening a streams to send message to cvw server
try {
//cvwsock is initialized to null with new instance of class
cvwSock.getOutputStream().write(bs.toByteArray());
cvwSock.getOutputStream().flush();
catch (Exception v) {
System.out.println("ServerComm: Error opening Stream: " + v);
//Anothe class
public class SomeClass{
ServerComm server= new ServerComm()//creating instance of the above class
//some expressions
server.sendCmdToServer(command); //connValid in ServerComm is initialized to false again. to doesnt send command but returns
}.In the above code in SomeClass when intantiated the connValid variable is reinitialized to false and hence it returns when called server.sendCmdToServer(command). while the openConnection() is succesfull called from another class -
Advantages and disadvanteges with static methods
Hi,
Can anybody suggest me the advantages and disadvantages of static methods? In my project i am using templates which are used by different programs and in that templates i am using static methods.
It is web application. is there any problems if made methods as static in templates that are used by diferent clients?
Thanks
KarimullaA static method can't be overridden, and static methods are usually only used for some utility methods and other things which don't belong to the class. I would probably not make the methods static.
Kaj -
Is Using Static functions advisable from performance(speed) point of view
I was wondering if using a static function would be slower than using a normal function, especially when the function is to be accessed by multiple threads since the same memory area is used each time the static function is accessed from any of the threads. Thus is it right if I say that static functions are not suitable for multiThreaded access ?
I was wondering if using a static function would be
slower than using a normal function,Static functions are linked at compile time, while normal functions have to be linked based on the runtime type of the object they are called on. This lookup means that static function invocations are likely to be faster.
especially when
the function is to be accessed by multiple threads
since the same memory area is used each time the
static function is accessed from any of the threads.If you are talking about the code segment, where the function definition is held, there is only a single copy of each "normal" function as well. The code segment is also read-only, so there are no issues with multiple threads reading and executing the same code at the same time.
There are the normal issues with multi-threaded access to variables in static functions that exist with normal functions.
Thus is it right if I say that static functions are
not suitable for multiThreaded access ?Static functions are no safer than non-static functions in terms of thread safety. On the other hand, it is no more dangerous having multiple threads calling a static function than having multiple threads calling a non-static function on the same object. Exactly the same thread safety techniques apply whether you are working in a static or a non-static context.
With the above in mind, there is a great deal of design difference between static functions and non-static functions. They mean very different things when creating a system, and an operation that is suited for a static function is very likely not appropriate in a non-static context, and vice versa. The important thing is to make sure the design is appropriate for what the system is trying to do.
The most common use of static functions is for object creation... The Factory design pattern uses static methods to create objects of a given type, the Singleton design pattern uses static methods to allow access to itself. -
I have a static method in my class .
Now i want to change my class to Distributed class
So what to do with that static method ...
I can't take in interface , so how i can call that method
Sunil VirmaniThe pre condition of all the remote methods is that they should have been declared in the interface implementing RemoteInterface. Now its been discussed in detail in this forum already why we cannot have static methods declared in the interface therefore by nature not being polymorphic u cannot use static methods for the aforesaid purpose.
-
Static methods, or not...
Ok, i've got a class with around 50 or so methods in it. im going to have around a hundred of these classes going at once. my question is: should i make all the methods static, and then pass in an instance of a class to work on? would that use less memory, or be beneficial in any way? im probably completely wrong, but i wanted to check anwyays, just in case..
so, for example
public void stuff(){
x++;
turning into
public void stuff(SomeClass target){
target.x++;
}For each method there is (generally) one and only one implementation loaded into memory. Having 10 thousand instances of a class does not create copies 10 thousand copies of the methods. No, using static methods would be a waste of your energy and probably be a rather poor design.
Chuck -
Static methods. Why?
I understand what static means, and that each class has only ONE copy of its static variables and methods.
I an see the benefits of using static variables, but i cant seem to get my head round the benefits of using static methods.
What is the advantage of this, and is there a common situation where they are appropriate? (not main)
CheersI don't think static exists to prevent namespace conflicts. I think that the reason for static to exist is just as I described it: When you've got some task that is appropriate to be performed by a specific class, but that doesn't make sense to be associated with a particular instance of that class.
For example, String.valueOf. It's appropriate for the String class to have a method that returns the String representation of anything you feed to it (so it's in the String class) but it doesn't make sense for that method to be associated with a particular instance of String (so it's static). After all, you don't yet have a String to operate on--you're producing the String.
Which raises another interesting point: I wonder what the design decision was that led to
String.valueOf(int)
String.valueOf(long)
String.valueOf(Object)
etc.
instead of
new String(int)
new String(long)
newString(Object)
etc.
I've used both patterns in my own work, but I don't really have any good criteria for picking one over the other.
One thing that comes to mind for the general case is that with the static method, you can return a subclass, which you can't do with a constructor. Conversely, with a constructor, the caller knows exactly which class he'll get, whereas with a static method he doesn't. Of course, these points don't apply to String, as it's final.
I'm new to java, but as far as I can tell, "static"
means "global". The reason for having them in classes
is mainly to prevent name conflicts. For instance,
you could have an Array object, and a List object, and
both could have sort() methods, but they may be very
different types of methods. By forcing sort() to be a
member of a class, instead of a global identifier, you
have Array.sort() and List.sort(), which is much
safer.
It seems that the java designers went to great lengths
to make sure there are no namespace conflicts in the
language. Maybe they even went a bit too far in this
sometimes. -
Hi,
I have a doubt using static methods:
If 2 users call the same static method wih diferente parameters, the parameters of first user are changed?
Thanks,
rjcI already read that the only problem is if i acess
and change static variables, in these cases i have
to synchronize the method, is this true?Certainly, it is. If more than one thread are trying to change the same "thing" by using a method, you have to synchronize this method. Or you can synchronize this "thing", too.
Maybe you are looking for
-
I recently bought an Ipod touch 2nd gen, (Ebay). It's in great shape and seemed to be wiped clean. When I connect (via windows computer) to Itunes with usb cord the Ipod icon shows, but the only function you can do is eject. When its in the upper rig
-
Storage space for sub mail accounts
Does anyone know how I can allocate more storage space for my additional mail accounts? I ran out of space and purchased another 2gb of storage on my .mac account. However, none of this space is allocated to my additional mail accounts i.e. all of it
-
WL 7.0 Node Manager - auto restart after system boot fails
I have configured node manager to automatically restart managed servers on my Solaris 2.8 host. When I kill the managed server from the command line, node manager automatically restarts the managed server just as I would expect. But when I reboot the
-
Hi there, I'm looking for a BAPI or FM that has the fields that I need to create a customer. I need to fill the "Withholding tax information", it is in the Company Code data. I can't find this data in the BAPI BAPI_CUSTOMER_CREATEFROMDATA1 and neithe
-
Hi, I've 2 units of WLSE, performing redundancy, and 2 WDS configured. In the WDS, at the WNM config, I've enter the virtual IP of the WLSE, but it give a message of "NOT AUTHENTICATED".. May I know why is that?? Thanks.