Singleton Class using a constructor not a getInstance method

Hi,
I have a class with a couple of contructors, the class is instantiated many times in the application.
Is there any way by which I can return a single instance of the class when the contructor is called ?.
I dont want to declare a get instance method to return a single instance is it somehow possible to do this in the contructor itself.
This is done so I dont have to refactor the whole application and change all the places where this class is instantiated.
Example
XXXClass xxx = new XXXClass();
every time new XXXClass() is called the single instance of the class must be returned.
I dont want to implement
XXXClass xxx = XXXClass.getInstance();
Thanks in advance
Rgds
Pradeep Thomas

The short answer to your question is No. If your class has accessible constructors and your code calls "new" then there will be multiple instances of the corresponding objects.
Possible ways round your problem are to use static variables in place of instance variables or to use your existing class as a wrapper for another class that is instantiated only once. This second class should include all the variables and methods and the wrapper class would delegate all calls to it. This is not quite a singleton because there would still be multiple instances of the wrapper, but each instance would share the same variables and methods. You could also add a getInstance() method to the wrapper class so that new code could start to use it as a singleton.
Other than that, it's time to refactor! Good Luck.

Similar Messages

  • Singleton Class using a constructor not a get Instance method ?

    Hi,
    I have a class with a couple of contructors, the class is instantiated many times in the application.
    Is there any way by which I can return a single instance of the class when the contructor is called ?.
    I dont want to declare a get instance method to return a single instance is it somehow possible to do this in the contructor itself.
    This is done so I dont have to refactor the whole application and change all the places where this class is instantiated.
    Example
    XXXClass xxx = new XXXClass();
    every time new XXXClass() is called the single instance of the class must be returned.
    I dont want to implement
    XXXClass xxx = XXXClass.getInstance();
    Thanks in advance
    Rgds
    Pradeep Thomas

    Pradeep ,
    You see a constructor does not return anything
    when you tell java
    String str = new String();
    It is into the reference str that a Object of the type String is assigned and used ..
    If you want a single instance to exist in your application ..the best way is to use the singelton approach.
    Alternatively you could create one static instance of the object in a parent class and all the classes that inherit from it will then share access .

  • Obtaining list of classes used in an application

    I want to be able to obtain a list of all the classes and interfaces that an application uses
    I have been looking at the Class Object but with limited success
    I can get only limited things from the class
    eg the superclasses, interfaces, innerclasses, and public variables
    but I want to be able to get which private classes are used also
    the code below shows my test code to get info about a class
    Class testClass = (new java.awt.Panel()).getClass();
    Class classList[] = testClass.getClasses();
    for(int i = 0; i < classList.length; i++)
         System.out.println("class "+i+" = "+classList);
    Class innerClassList[] = testClass.getDeclaredClasses();
    for(int i = 0; i < innerClassList.length; i++)
         System.out.println("innerClass "+i+" = "+innerClassList[i]);
    java.lang.reflect.Field fieldList[] = testClass.getFields();
    for(int i = 0; i < fieldList.length; i++)
         System.out.println("field "+i+" = "+fieldList[i]);
    java.lang.reflect.Field innerFieldList[] = testClass.getDeclaredFields();
    for(int i = 0; i < innerFieldList.length; i++)
         System.out.println("innerField "+i+" = "+innerFieldList[i]);
    Object interfaceList[] = testClass.getInterfaces();
    for(int i = 0; i < interfaceList.length; i++)
         System.out.println("interface "+i+" = "+interfaceList[i]);
    Class nextSuper = testClass;
    while(nextSuper != null){
         System.out.println("Class "+nextSuper);
         nextSuper = nextSuper.getSuperclass();
    The reason that I want to do this is:
    When I use an application I want to be able to get the version of each of the classes I use.
    Ideally I would build up a set of classes used in the application (and the classes that those classes use, etc, etc)
    as I did this I would filter for things that start with my class hierarchy.
    and I would save the public String of each class that stores the version.
    Then heypresto I would have a list of all the classes of mine that are used and their version numbers.

    The idea is to write your own class which extends classloader, then use an instance of that to load the program you're trying to examine. When java wants to use a class it calls a classloader giving it the class name and package e.g. "java.lang.String". The classloader then checks to see if the class is already there, and if not attempts to load it, usually from a .class or .jar file.
    When classes loaded with a particular class loader go looking for other classes they call the classloader than loaded them.
    So if you load your main program class through your own classloader then any classes it demands (and those they demand), will also be looked for through your classloader. Since class loading is a dynamic process you actually need to run the application (having loaded your main class use getMethod to get the main method then Method.invoke(..).
    Mind you if java -verbose:class does the job (and it looks to me like it does) that's a lot simpler.
    Just run your program with that and analyse the resulting list of load events.

  • Can not access the Instance Data of a Singleton class from MBean

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

  • Can not locate Java class using JNI within C++ DLL

    I am using trying to use JNI to call a Java class from C++. The Java class uses JMS to send messages to a JMS message queue. At first I coded the C++ in a console application that created the JavaVM and used JNI to access the Java class. All worked fine. Then I called the Java class using JNI from threads and ran into the problem of the Java class not able to locate the JMS related classes. This was solved by placing the following line in the constructor of the Java class.
    Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
    Then I moved the JNI code from a console application to a DLL in specific an extension DLL that is called by SQL Server or Oracle server. The DLL will use JNI to call the Java class and send messages to a JMS message queue.
    The problem I am having now when the DLL code is called by SQL Server the call to
    JNI_CreateJavaVM
    appears to work correctly but the call to find the Java class using
    jvmEnv->FindClass(pName)
    fails. It appears the is a class loading problem which occurs due to the fact JNI is called from a DLL. When the VM is created I pass the class path information using the statement
    -Djava.class.path=
    And as I stated before it all works when running from a console application. I am new to JNI and really need help in the form of some sample code that will solve this problem. I believe I need to somehow load the classpath information from the DLL but I can not find examples on how to do this using JNI. I have tried several ways using URLClassLoader and getSystemClassLoader from JNI and either it does not work or it crashes very badly.
    I used the following code to determine what the existing class path is and the string returns empty.
    jcls = jvmEnv->FindClass("java/lang/System");
    jmid = jvmEnv->GetStaticMethodID(jcls, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
    jstrClassPath = jvmEnv->NewStringUTF("java.class.path");
    jstr = (jstring)jvmEnv->CallStaticObjectMethod(jcls, jmid, jstrClassPath);
    m_jstr = (jstring)jvmEnv->NewGlobalRef(jstr);
    pstr = jvmEnv->GetStringUTFChars(m_jstr, 0);
    Can anyone please help with example code that will solve this problem. Thanks in advance for any help.
    Charles�

    I have determined the problem occurs when the application/component is compiled using VC 6.0. The test application was compiled using VC 7.1 and works correctly by locating the class path information. If the test application is compiled using VC 6.0 it has the same problem.
    The jvm.dll I am using is version 1.4.2.80. Currently this is not an option to compile all the applications that use JNI using VC 7.1 so can someone please tell me how to solve this problem.

  • To use a Threading Class for EJBs or not?

    I was wondering if someone can help me answer this question? I am going to have this class that will be used by the Beans to complete a transaction. Because I have several Beans that all need this one particular class to complete a transaction, I was wondering if it would be good to create this class in a cache type manner. Meaning this class will only be instantiated once when the server loads after that all the beans will only reference it through this class' getInstance() method. I know this class does not contain any data that needs to persist however I would like to avoid having mulitple instances of this one particular class. The class completes a rather long transaction process. It is not much from my side, but I have to wait a few seconds for the other application that I connect to, to complete the transaction, then finally get a return. This class does not do too much work, but it just needs to wait for a long time to get back a response. Since threads are lighter and cheaper than a complete process I was wondering if I should create this class that extends the thread. Below I have some basic code that can do this but I was wondering if this would be a good methodolgy for transaction heavy application. Sorry for making it too long. I have marked the class with X's to prevent the client who we connect to.
    public class XXXXXXX extends Thread {
    private static XXXXXXXX wconn = null;
    private XXXXXXXX xxc;
    private String response = null;
    public XXXXXXXX() {
    this.xxc = new XXXXXXXX ();
    * set properties *
    this.xxc.host = ""; //Connector ID
    this.xxc.port = 8800; //without SSL
    //this.xxc.port = 443; //SSL
    this.xxc.ssl = false; //SSL (if true, change port to 443!)
    this.xxc.compress = true; //compression
    this.xxc._native = true; // native request; MUST set to true for XML Pro
    this.xxc.keepalive = false; //indicates if the connection to the server should persist
    public void run()
    public static XXXXXXXX getInstance()
    return wconn;
    private other functions ....
    Thank You for any insight that you can provide.

    So you want to run something outside the containter. It doesn't matter whether you have a seperate app or just run inside the same JVM as the container. Once you are outside the container it doesn't matter how you implement it in terms of J2EE.
    It sounds to me like you just have a job and you are submitting that job for processing. You might want to examine what happens when more than one thread accesses that instance at the same time but other than that it works. You might also want to look at what happens if one or more of the other systems are down (where persisting the job on your side might make sense.)

  • Calendar.getInstance method not loading userdefined locale classes

    Hi
    In JDK 6
    I have implemented CalendarData_en_AT class for locale(en, AT) which is a user defined locale(not defined in jre). I see that when I try to load the locale using Calendar.getInstance method it loads CalendarData_en.class
    When further debugged, I found that it picks up only the locales that are specified in LocaleMetaDataInfo class
    What needs to be done so that when we call Calendar.getInstance(new Locale(en, AT)) it loads CalendarData_en_AT.class
    Thanks
    -Beena

    I have a class CalendarData_en_AT.java
    public class CalendarData_en_AT extends LocaleNamesBundle
    public CalendarData_en_AT()
    protected final Object[][] getContents()
    return (new Object[][] {
    new Object[] {
    "firstDayOfWeek", "2"
    }, new Object[] {
    "minimalDaysInFirstWeek", "4"
    The compiled class is enclosed in a .jar file and have been placed in jre/lib/ext
    Now from my test class
    if I call Calendar.getInstance(new Locale("en","AT")).getFirstDayOfWeek()
    it should return 2, but as of now it returns 1, reason being it loads CalendarData_en.class and not CalendarData_en_AT.class which is user implemented

  • Class with private constructor can be extended or not

    Hi All,
    I have a doubt.
    if a class has private constructor and there are some methods in this class.Can this class be extended and if yes how can we call its method in subclass?
    Thanks
    Sumit

    Karanjit wrote:
    If a class contains only private constructors, then it cannot be extended.Err... not the whole story!
    public class Sabre20090603a
        static class Fred extends Sabre20090603a
            Fred()
                super();
        private Sabre20090603a()
    }

  • How to make Singleton Class secure

    I have a Singleton class which I instantiate using reflection by a call to a public getInstance method that return the object from a private constructor. I have to use reflection as I dont have any other options since my class instantiation is decided on runtime. How will I secure other form instantiating the same class again by using reflection on my private constructor? Any ideas?

    How much do these different implementations of your singleton have in common? What I'm getting at is, is there some common code you could extract out of them all, and make that a singleton in it's own right? Needing to do this sort of hacking is often a sign you're fudging something together, that could be solved more elegantly. We use the Singleton pattern generally when the state of the object needs to exist exactly once. Can you extract that from the disparate objects?
    The singleton classes that I load do not have anything in common. They are all similar but unique, and independant in their own respect. I will have to decide only on what singleton object I have to load in runtime, based on certain criterion. This is done by reflection, by a call to the public getInstance() method of the respective singleton classes, since I am deciding on runtime. My problem is that can I prevent others from accessing my private constructor from outside the class using reflection, which enables them to create another duplicate object. Can I restrict them to use only my getInstance() method instead?? I know this is hacking to access the private members, but I want to know whether there is any way where I can restrict this hacking???In the above code I dont want these statements to work at any case
    java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
    c[0].setAccessible(true);
    A anotherA  = (A) c[0].newInstance(new Object[]{"Duplicate"});

  • SINGLETON CLASSES QUESTIONS

    Hello,
    Could someone please explain what the following code does? How does it work? How can I use it in the real program?
    More importantly, if you are kind enough, please give me some examples how to use singleton class? Why do we have to use this class?
    I spent two days on this topic, Singleton, but my mind still goes blank.....
    thank you.
    public class Singleton
    static public Singleton getInstance()
    if(theInstance == null)
    theInstance = new Singleton();
    return theInstance;
    protected Singleton()
    //initializing instance fields
    //instance fields and methods
    private static Singleton theInstance = null;

    Hello,
    Could someone please explain what the following code
    does? The code defines a class called Singleton. :)
    How does it work? The static method "getInstance()" returns an object of type Singleton. Static methods can be called without having an instance of a class, so you can type:
    Singleton.getInstance();
    How can I use it in the
    real program?This class is pretty useless in a real program. The point of this class is to show you how the Singleton design pattern can be implemented in Java. Any useful Singleton object needs to have additional properties and methods. (Oh I know someone will say that you can still use this class for something, but I'm trying to explain something here...)
    More importantly, if you are kind enough, please give
    me some examples how to use singleton class? Sure, here's an example of a singleton: Suppose you want a debugging class that will simply write text to a file. You want to only have one instance of this class (i.e. you don't want to have multiple log files, you want to provide one single interface point for this):
    class LoggerSingleton
      private static final String LOGFILENAME = "log.txt";
      private BufferedWriter write = null;
      private LoggerSingleton instance;
      synchronized static public LoggerSingleton getInstance()
      { if(instance == null)  instance = new LoggerSingleton(LOGFILENAME);
        return instance;
      protected LoggerSingleton(String filename)
        try {
          write = new BufferedWriter(new FileWriter(filename));
          write.write("Log File Opened");
          write.newLine();
          write.flush();
        catch(IOException ioe)
          System.err.println("Error!  LoggerSingleton could not be initialized");
          ioe.printStackTrace(System.err);
          System.exit(1);
      public log(String text)
        write.write(text);
        write.newLine();
        write.flush();
    }This class will make sure you only have one log file and ensures that all classes are using it:
    class FirstClass {
      SecondClass second = new SecondClass();
      public FirstClass() {
        LoggerSingleton.getInstance().log("Inside FirstClass' constructor");
      public void func1() {
        LoggerSingleton.getInstance().log("Inside FirstClass.func1()");
    class SecondClass {
      public SecondClass() {
        LoggerSingleton.getInstance().log("Inside SecondClass' constructor");
    Why do we have to use this class?You don't have to use this class, but it is one technique to ensure that multiple instances of an object are not instantiated. It is also a technique to ensure that there is only one interface point across the application (you can also use a Singleton object to implement the Bridge and Factory design patterns). The Singleton technique is achieved by making the constructor protected, which means that only methods inside the class (and package) can construct instances of Singleton. The only time an instance of Singleton is constructed is the first time that getInstance() is called.
    I spent two days on this topic, Singleton, but my mind
    still goes blank.....
    Still blank?

  • To ragnic and other about Singleton class

    Hi ragnic. Thanks for your reply. I posted the code wrong. Heres' my correct one.
    I have a GUI first loaded information and the information is stored in a databse, I have some EJB classes..and my singleton class ABC has some method to access to the EJB..
    so my first GUI will gather info using singleton class and later if I click on
    a button in my first GUI class, will pop up another frame of another class , this class also need to class setPassword in my Singleton..
    are my followign codes correctly??
    iS my Class ABC a SINgleton class? thanks
    Is my class ABC use as single correctly. And It is called from other classes is also correct?
    I'm new to java and like to learn about Singleton class.
    But I really dont' understand it clearly after reading many examples of it.
    I have a project to convert my class abc to a singleton.
    But I dont know how to do it.
    In my class(soon will become a singleton) will have few methods that later I need to use it from another class A and class B.
    I have a GUI application that first load my class A..and my class will call
    class abc(singleton) to get some information from it.
    and then in class A has a button, if I click on that button I will call SIngleton class again to update my password, in the singleton class has method calls updatePassword. But I dont know how to call a singleton from other class.
    I have my code for them below:
    1)public class ABC //attempt using a singleton
    private static ABC theABC = null;
    private ABC(){}
    public synchronized static ABC getABC()
    if(theABC == null)
    theABC= new ABC();
    return the ABC;
    public void updateUserInfo(SimpleUser user)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    uc.updateUserInfo(user, userHome);
    } catch(HomeFactoryException hfe) {
    hfe.printStackTrace();
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    re.printStackTrace();
    throw new DelegateException(re);
    } catch(CreateException ce) {
    ce.printStackTrace();
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    fe.printStackTrace();
    throw new UserNotFoundException();
    public SimpleUser getID(String id)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    SimpleUser su = uc.getID(id, userHome);
    return su;
    } catch(HomeFactoryException hfe) {
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    throw new DelegateException(re);
    } catch(CreateException ce) {
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    throw new UserNotFoundException();
    public void setPassword(String lname,String pw)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    uc.setPassword(lname,pw, userHome);//assume that all lname are differents.
    } catch(HomeFactoryException hfe) {
    hfe.printStackTrace();
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    re.printStackTrace();
    throw new DelegateException(re);
    } catch(CreateException ce) {
    ce.printStackTrace();
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    fe.printStackTrace();
    throw new UserNotFoundException();
    }//Do I have my class as a Singleton correctly???
    2)//Here is my First Frame that will call a Singleton to gather user information
    public A(Frame owner)
    super(owner, "User Personal Information",true);
    initScreen();
    loadPersonalInfo();
    * This method instantiates all the GUI widgets and places them into panels and
    * onto the frame.
    private void initScreen()
    txtFname = new JTextField(20);
    txtLname=new JTextField(20);
    btnsave =new JButton("Save");
    btnChange= new JButton("Click here to change PW");//when you click this button there will be a frame pop up for you to enter informaton..this iwll call class B
    JPanel pnlMain=new JPanel();
    JPanel pnlFname= new JPanel();
    pnlFname.setLayout(new BoxLayout(pnlFname, BoxLayout.X_AXIS));
    pnlFname.setBorder(BorderFactory.createEmptyBorder(0,87,0,90));
    pnlFname.add(new JLabel("First Name:"));
    pnlFname.add(Box.createRigidArea(new Dimension(5,0)));
    pnlFname.add(txtFname);
    JPanel pnlLname= new JPanel();
    pnlLname.setLayout(new BoxLayout(pnlLname, BoxLayout.X_AXIS));
    pnlLname.setBorder(BorderFactory.createEmptyBorder(0,87,0,90));
    pnlLname.add(new JLabel("Last Name:"));
    pnlLname.add(Box.createRigidArea(new Dimension(5,0)));
    pnlLname.add(txtLname);
    pnlMain.add(pnlFname);
    pnlMain.add(pnlLname);
    pnlMain.add(btnsave);
    pnlMain.add(btnChange");
    btnSave = new JButton("Save");
    btnSave.setActionCommand("SAVE");
    btnSave.addActionListener(this);
    btnCancel = new JButton("Cancel");
    btnCancel.setActionCommand("CANCEL");
    btnCancel.addActionListener(this);
    JPanel pnlBottom = new JPanel();
    pnlBottom.setLayout(new BoxLayout(pnlBottom, BoxLayout.X_AXIS));
    pnlBottom.setBorder(BorderFactory.createEmptyBorder(25,55,0,0));
    pnlBottom.add(btnSave);
    pnlBottom.add(Box.createRigidArea(new Dimension(25,0)));
    pnlBottom.add(btnCancel);
    pnlMain.add(pnlBottom);
    this.setContentPane( pnlMain);
    setSize(500,500);
    GraphicUtilities.center(this);
    theABC=ABC.getABC();
    //Do I call my ABC singleton class correctly??
    private void loadPersonalInfo()
    String ID= System.getProperty("user.name");
    SimpleUser user = null;
    try {
    user = ABC.getID(ID);
    //I tried to use method in ABC singleton class. IS this correctly call?
    } catch(UserNotFoundException nfe)
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered.",
    "User Not Found",JOptionPane.WARNING_MESSAGE);
    System.exit(0);
    } catch(DelegateException de) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    currentUser = user;
    txtFname.setText(currentUser.getFirstName());
    txtLname.setText(currentUser.getLastName());
    //This information will be display in my textfields Fname and Lname
    //I can change my first and last name and hit button SAVE to save
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equals("SAVE")) submitChanges();
    if(e.getActionCommand().equals("CHANGE_PASSWORD")) {
    changepassword=new ChangePassword(new Frame(),name,badgeid);
    public void submitChanges(){
    String currentNTUsername = System.getProperty("user.name");
    SimpleUser user =null;
    try {
    user = theABC.getID(ID);
    user.setFirstName(txtFname.getText().trim());
    user.setLastName(txtLname.getText().trim());
    currentUser = user;
    theABC.updateUserInfo(currentUser);
    //IS this correctly if I want to use this method in singleton class ABC??
    } catch(UserNotFoundException nfe)
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",
    "User Not Found",JOptionPane.WARNING_MESSAGE);
    } catch(DelegateException de) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    this.setVisible(false);
    3) click on ChangePassword in my above GUI class A..will call this class B..and in this class B
    I need to access method in a Singleton class- ABC class,,DO i need to inititates it agian, if not what should I do? thanks
    package com.lockheed.vista.userinfo;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.tree.*;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import java.io.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.colorchooser.*;
    import javax.swing.filechooser.*;
    import javax.accessibility.*;
    import java.beans.*;
    import java.applet.*;
    import java.net.*;
    import org.apache.log4j.*;
    import com.lockheed.common.gui.GraphicUtilities;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import vista.user.UserServicesDelegate;
    import vista.user.SimpleUser;
    import vista.user.UserNotFoundException;
    import vista.user.*;
    import com.lockheed.common.ejb.*;
    import com.lockheed.common.gui.*;
    import com.lockheed.vista.publish.*;
    * This program allow users to change their Vista Web Center's password
    public class ChangePassword extends JDialog
    implements ActionListener{
    protected final Logger log = Logger.getLogger(getClass().getName());
    private UserServicesDelegate userServicesDelegate;
    private User currentUser = null;
    private JPasswordField txtPasswd, txtVerifyPW;
    private JButton btnSubmit,btnCancel;
    private JLabel lblName,lblBadgeID;
    private String strBadgeID="";
    * This is the constructor. It creates an instance of the ChangePassword
    * and calls the method to create and build the GUI.
    public ChangePassword(Frame owner,String name,String badgeid)
    super(owner, "Change Password",true);
    initScreen(name,badgeid);//build the GUI
    * This method instantiates all the GUI widgets and places them into panels and
    * onto the frame.
    private void initScreen(String strname,String strBadgeid)
    txtPasswd = new JPasswordField(20);
    txtVerifyPW=new JPasswordField(20);
    txtPasswd.setEchoChar('*');
    txtVerifyPW.setEchoChar('*');
    JPanel pnlMain=new JPanel();
    pnlMain.setLayout(new BoxLayout(pnlMain, BoxLayout.Y_AXIS));
    pnlMain.setBorder(BorderFactory.createEmptyBorder(20,0,20,0));
    JPanel pnlPW=new JPanel();
    pnlPW.setLayout(new BoxLayout(pnlPW, BoxLayout.X_AXIS));
    pnlPW.setBorder(BorderFactory.createEmptyBorder(0,96,0,30));
    pnlPW.add(new JLabel("Password:"));
    pnlPW.add(Box.createRigidArea(new Dimension(5,0)));
    pnlPW.add(txtPasswd);
    JPanel pnlVerifyPW=new JPanel();
    pnlVerifyPW.setLayout(new BoxLayout(pnlVerifyPW, BoxLayout.X_AXIS));
    pnlVerifyPW.setBorder(BorderFactory.createEmptyBorder(0,63,0,30));
    pnlVerifyPW.add(new JLabel("Verify Password:"));
    pnlVerifyPW.add(Box.createRigidArea(new Dimension(5,0)));
    pnlVerifyPW.add(txtVerifyPW);
    JPanel pnlTop= new JPanel();
    pnlTop.add(pnlPW);
    pnlTop.add(Box.createRigidArea(new Dimension(0,10)));
    pnlTop.add(pnlVerifyPW);
    pnlMain.add(pnlTop);
    btnSubmit = new JButton("Submit");
    btnSubmit.setActionCommand("SUBMIT");
    btnSubmit.addActionListener(this);
    btnCancel = new JButton("Cancel");
    btnCancel.setActionCommand("CANCEL");
    btnCancel.addActionListener(this);
    JPanel pnlBottom = new JPanel();
    pnlBottom.setLayout(new BoxLayout(pnlBottom, BoxLayout.X_AXIS));
    pnlBottom.setBorder(BorderFactory.createEmptyBorder(25,55,20,30));
    pnlBottom.add(btnSubmit);
    pnlBottom.add(Box.createRigidArea(new Dimension(25,0)));
    pnlBottom.add(btnCancel);
    pnlMain.add(pnlBottom);
    this.setContentPane( pnlMain);
    setSize(350,230);
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equals("CANCEL")) this.setVisible(false);
    if(e.getActionCommand().equals("SUBMIT")) submitPW();
    * This method is called when the submit button is clicked. It allows user to change
    * their password.
    public void submitPW(){
    myABC= ABC.getABC();//Is this correct?
    char[] pw =txtPasswd.getPassword();
    String strPasswd="";
    for(int i=0;i<pw.length;i++){
    strPasswd=strPasswd+pw;
    char[] vpw =txtVerifyPW.getPassword();
    String strVerifyPW="";
    for(int i=0;i<vpw.length;i++){
    strVerifyPW=strVerifyPW+pw;
    if((strPasswd==null)||(strPasswd.length()==0)) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not enter a password. Please try again.",
    "Invalid Password",JOptionPane.ERROR_MESSAGE);
    if((!strPasswd.equals(strVerifyPW)))
    //password and verify password do not match.
    JOptionPane.showMessageDialog(new JDialog(),"Your passwords do not match. Reenter and try again.",
    "Invalid Password",JOptionPane.ERROR_MESSAGE);
    try
    myABC.setUserPassword(strPasswd);//try to use a method in Singleton class
    txtPasswd.setText("");
    txtVerifyPW.setText("");
    this.setVisible(false);
    } catch(DelegateException e) {
    JOptionPane.showMessageDialog(new Frame(),
    "Error.",
    "Unable to change password information.",JOptionPane.WARNING_MESSAGE);
    } catch(UserNotFoundException e) {
    JOptionPane.showMessageDialog(new Frame(),
    "Error.",
    "Unable to change password information.",JOptionPane.WARNING_MESSAGE);
    And ofcourse I have other EJB classes to work with these classes.
    ***It compiles okey but when I ran, it say "NullPointerException"
    I think I call my Singleton wrong.
    Please help me.thanks

    1. When replying, use <reply>, don't post a new topic.
    2. Implementing a singleton is a frequently asked question. Search before you post.
    3. This is not a question about Swing. A more appropriate forum would be "New To Java Technology" or perhaps "Java Programming", but see point 1.
    4. When posting code, keep it short. It increases the chance of readers looking at it. And in composing your shorter version for the forum, you just may solve your problem.

  • Singleton class + JTable mouseClicked

    Hi,
    I have a problem with this topic:
    singleton class OR create new class and use one function (not a static func) of this class from else class.
    I have singleton class that return JScrollPane with table, in this table I have tasks..
    in this class I have: public void mouseClicked(MouseEvent e) function.
    when the user clicked --> I create another JTable (table with sub tasks)
    and if the user clicked in this table, I create another JTable (table with sub sub tasks).............................
    I need your help because: if the class that create a JTable singleton type, then I can not get another mouseClicked of jtable that below the new jtable (I can't get another mouseClicked of sub tasks table if I created the sub sub tasks table...).
    But, if I create everytime NEW class that return the scroll JTable --> I get different problem:
    I need to use with some functions from scroll JTable class and I don't know how to do it..I can't do: TaskTable.getInstance().getMyFunc();
    This function must to be in this class, and not static!
    I'm new :) maybe I don't know some else way to get function from regular class.
    Sorry about my english.
    I'm really need your help :)
    Thasks.

    ..if I create everytime NEW class that return the scroll JTable --> I get different problem:
    I need to use with some functions from scroll JTable class and I don't know how to do it..
    TaskTable t1 = new TaskTable();
    t1.getMyFunc();

  • How to implement a singleton class across apps in a managed server}

    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once.
    Am i missing something here ? or did i implement it wrong..?
    public class Test
       private static Test ref ;
       private DataSource X; 
       static int Y;
       long Z ;  
       private Test ()
          // Singleton
           Z= 100 ;
       public static synchronized Test getinstance()  throws NamingException, SQLException
          if(ref == null)
             ref = new Test() ;        
             InitialContext ic = new InitialContext();
             ref.X = (DataSource)ic.lookup ("jdbc/Views");
          return ref ;       
       public Object clone()throws CloneNotSupportedException
           throw new CloneNotSupportedException();
       public int sampleMethod (int X) throws SQLException
    public final class Filter implements Filter
         public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
              try
                   Test ref = Test.getinstance();
                   log.logNow(ref.toString());
    }Edited by: Tom on Dec 8, 2010 2:45 PM
    Edited by: Tom on Dec 8, 2010 2:46 PM

    Tom wrote:
    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .Two apps = two instances.
    Basically by definition.
    >
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once. A class is loaded by a class loader.
    Any class loader that loads a class, by definition loads the class.
    A VM can have many class loaders. And far as I know every JEE server in existance that anyone uses, uses class loaders.
    And finally there might be a problem with the architecture/design of a JEE system which has two applications but which is trying to solve it with a singleton. That suggests a there might be concept problem with understanding what an "app" is in the first place.

  • Singleton class

    Hi everybody
    Need to programm a calculation project and got the advice to use an singleton class. What the h... is that, how does it work and what is it good for. Anyone who can give me code samples and a short explanation?

    Slight correction: There are two main ways to implement singleton. In the way fluca has shown, you have to synchronize getInstance. The other way is to assign the instance at declaration time, and skip the check for null in getInstance.
    These were just illustrated quite well by jschell or DrClap or jsalonen or somebody within the last few days, probably either on this forum or on New to Java Technology. (Might have been Advanced Lang Topics, but I doubt it). Do a search on Singleton and you'll find that thread (and a lot more, I imagine).
    Hi,
    well a singleton is a class, from which is
    instantiable only one object for every JVM.
    Tipically it's obtained dclaring private (or
    protected) the constructor, and using a static method
    (and an internal staic reference) to get the
    instance.
    For example:
    public class MySing
         private MySing()
         // reference to myself
         private static myself;
         // get the instance
         public static MySing getInstance()
              if(myself==null)
                   myself=new MySing();
              return myself;
    A singleton class is useful for object that must be
    used by various threads, but that at the same time
    needs to mantaine a particular
    coerence. For example, if you deploy a database 100%
    pure Java, then it must run as singleton, because two
    threads must obtain the same reference, and can't
    create two different database.
    Hope this helps

  • [svn:osmf:] 10996: Changing MediaElementLayoutTarget to be constructed via a static ' getInstance' method, instead of by its constructor.

    Revision: 10996
    Author:   [email protected]
    Date:     2009-10-19 07:45:26 -0700 (Mon, 19 Oct 2009)
    Log Message:
    Changing MediaElementLayoutTarget to be constructed via a static 'getInstance' method, instead of by its constructor. This prevents the construction of multiple instances that reference one single media-element. Updating client code accordingly.
    Extending layout unit tests. Adding a custom renderer, checking calculation and layout passes invokation counts.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/composition/CompositeViewableTrait.as
        osmf/trunk/framework/MediaFramework/org/osmf/composition/ParallelViewableTrait.as
        osmf/trunk/framework/MediaFramework/org/osmf/composition/SerialViewableTrait.as
        osmf/trunk/framework/MediaFramework/org/osmf/gateways/RegionSprite.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/DefaultLayoutRenderer.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/LayoutContextSprite.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/LayoutRendererBase.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/MediaElementLayoutTarget.as
        osmf/trunk/framework/MediaFramework/org/osmf/utils/MediaFrameworkStrings.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/composition/TestParallelViewableTrai t.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/gateways/TestRegionSprite.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/layout/TestDefaultLayoutRenderer.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/layout/TestLayoutUtils.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/layout/TestMediaElementLayoutTarget. as
    Added Paths:
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/composition/CustomRenderer.as

    AlexCox, can you clarify that once you get the default model out and save it in the temp var, that your ONLY access to the data is then through temp and never through the JList methods?
    Quick question for everyone: Are any of you using JList.setListData to set you initial dataset? I think that is where the bug lies. When I do not use it and start with an empty list, I am able to add to that list, and then remove from that list using the following line:
    ((DefaultListModel)myList.getModel).remove(###);
    And this cast works everytime.
    But when I start that list out with some data such as:
    myList.setListData(myStringArray);
    and then try to execute the above line, boom! I get the ClassCast exception.
    I think setListData creates a whole new model which is an inner class to JList (which seems stupid when DefaultListModel seems made for this).
    Just my thoughts on where the problem lies. I'll add my data directly to the list and see if that works better.
    PK

Maybe you are looking for

  • Disable access to the cloud storage feature for Creative Cloud for Teams?

    Is it possible to disable access to Creative Cloud Files when using Creative Cloud software for Teams/Volume Licensing customers? We're considering moving to Creative Cloud subscriptsions instead of traditional licensing and the ability to turn this

  • Sending photos in body of e-mail

    I want to send an e-mail with a string of photos from iPhoto showing in the body of the e-mail. I get e-mails like that all the time and I had no problem doing that on a pc but I don't seem to be able to do that on a Mac. My friend who had had a Mac

  • Country code, language key.

    Hi, Uploading the data from flat file to crm using  bapi. In flat file they (legacy) provided country is like INDIA but i need IN only. Is there any function module  for this conversion. and also for language: they provided english. insted of EN. ple

  • Select one choice : fetch values on demand

    Hi, we are using Jdev 11.1.1.3.0. In ADF application jsff page, we have 10 LOV fields in the page, each having more than 8000 values. The page is extremly slow while loading it. When we remove all the SelectOneChoice and run the page, it is lighting

  • ORA-01446: cannot select ROWID from, or sample, a view with DISTINCT, GROUP BY, etc.

    Dears, i have this problem after i create tabular from depend on view ORA-01446: cannot select ROWID from, or sample, a view with DISTINCT, GROUP BY, etc. this a query that i use select "INVOICE_DET", "INVOICE_DET" INVOICE_DET_DISPLAY, "INVOICE_ID",