How to declare a class to be singleton ?

A singleton pattern says that it will generate only one object all in a whole.
Such a class is called to be singleton!
How can we make a class in java to be singleton, that it generates only one object and further object generation is violated ?

Like:
public class MySingleton {
  private MySingleton() {  // private constructor prevents new from outside
... contents
  public static MySingleton getInstance() {  // get unique instance
     return _inst;
  private static MySingleton _inst = new MySingleton();
  }

Similar Messages

  • How to declare ftp in File class. I want to display filename of file in FTP

    How to declare ftp in File class. I want to display filename of file in FTP server.
    I try
    File f2= new File("ftp://abc:abc1111@ABC/file");
                   String n[] = f2.list();
                   System.out.print(n[0]);
                   Vector filename = null ;
                   for (int i2 = 0; i2 < n.length; i2++) {
                        filename.add(n[i2]);
    but it is not work
    Thank you.

    You can use Jakarta's net-package to connect to a FTP server.
    Download it here:
    http://jakarta.apache.org/site/downloads/downloads_commons-net.cgi
    Here's a small demo:
    import org.apache.commons.net.ftp.*;
    public class FTPTest {
        private boolean isConnected;
        private FTPClient client;
        public FTPTest() {
            isConnected = false;
            connect();
        private void connect() {
            String server = "server.org";
            String username = "user";
            String password = "password";
            client = new FTPClient();
            try {
                client.connect(server);
                client.login(username, password);
                String[] files = client.listNames();
                for(int i = 0; i < files.length; i++) {
                    System.out.println(files);
    isConnected = true;
    disconnect();
    catch(Exception e) {
    e.printStackTrace();
    private void disconnect() {
    if(isConnected) {
    try {
    client.disconnect();
    isConnected = false;
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args) {
    new FTPTest();

  • 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 test a class with array which is being declared?

    Dear All
    I am doing a question which involved the day of the week.
    I had written a class which is name WeekDay and here is the code :
    public class WeekDay
    private int index;
    private static String[]dayStrings = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
    public WeekDay(int idx)
    index = idx;
    public int getIndex()
    return index;
    public static String nextDay(int index)
    index+=1;
    return dayStrings[index];
    The above compile well with no issue.
    Here is the problem which i need to seek your help, I had created a program to test the above program.
    But I am not sure how to test it.
    Here is what I had written :
    public class TestWD
    public static void main(String[]args)
    System.out.println("Please key in a digit to get the day of the week\n");
    System.out.println("Sun, Mon, Tue.....Sat is represented by 0,1,2,3...6");
    int idx = Integer.parseInt(args[0]);
    WeekDay wd = new WeekDay(dayStrings[]); // I can't seem to declare this line.
    My question how can I test the above program ?? I can't seem to be able to declare a "wd" from WeekDay. The dayStrings wich i had declared in the WeekDay class is a String array. But how can I declare a suitable line in my test program in order for me to test my program?
    What I wanted to do is to get the above line running and than I will proceed on to code it to display the day after a day...for example, if today is Wednesday and when I run the wd.nextDay(index). It will return me Thursday!
    But I am not sure how to declare the above...please enlighten me.
    Thank you.

    Hi
    Thank you for helping but when I compile my program. It seem fine but when I execute it, it prompt me with an error message :
    code}public class TestWD
    public static void main(String[]args)
    System.out.println("Please key in a digit to get the day of the week\n");
    System.out.println("Sun, Mon, Tue.....Sat is represented by 0,1,2,3...6");
    * int idx = Integer.parseInt(args[0]);*
    WeekDay wd = new WeekDay(idx);
    System.out.println(wd.nextDay(idx));
    }{java.lang.ArrayIndexOutOfBoundsException: 0
         at TestWD.main(TestWD.java:8)
    Edited by: SummerCool on Nov 1, 2007 2:53 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to declare class for library like function

    Hey guys I want to declare class Math and define method subtrction so that i can use it in other class like
    package p1
    public class Math
    Math( ){}
    int Subtration ( int a, int b)
    return (a-b)
    package p2
    import p1.*;
    Public Class Test
    Test()
    int somenumber=Math.Subtration(3,4);
    For some reason I cannot see any methods inside Math class. when i type
    somenumber = Math. it show me only one option and that is 'class' instead of mathods inside Math. any thoughts?
    thx

    Yes I am aware of Math class in java. The question is
    how do i declare a class and call it's method in some
    other class with out declaring an object of that
    class.
    Like I can just call Math.sqrt(4) with out
    specifically declaring Math as an object. I want to
    declare my own class which has some methods I wish to
    call in some other class.MyClass.someMethod(). Just make sure that the methos is actually declared static. I suggest looking up the static keyword to find out what it means.

  • How to declare interface within a class

    1. I want to declare interface within a class. How can i do that & whats the advantage ?
    2. How to declare class within a interface ?
    Can anybody tell me the concept ?/
    Thanks in advance
    madhu

    Classes and interfaces are types.
    What is the advantage of declaring a type within another one?
    Do you know what is the advantage of declaring a class within another class?

  • How to add a class in a project?

    Hello!
    i'm a beginner in developing and i don't know how to add a class in a project in Sun Java Wireless toolkit 2.5.2...
    The name of my project is essai2 and i already put a class, LogoMIDlet and now i want to put my new class ComBasique, how can i do that?
    and do you know if there is a program for bluetooth in order to connect my Nokia 6680 to another device that have a bluetooth?
    thanks a lot for your answer!
    Sophie

    how to change the class name after the project is created.In NetBeans, right click the class name either in the declaration or constructor, select Refactor --> Rename... and follow the dialog.
    You can refactor --> rename anything that is not in a guarded block. For those, there are options via the properties window.
    db

  • How to declare value binding to array list element in a pojo?

    I have a POJO called P, that contains an ArrayList member called w.
    class P {
    private ArrayList w = new ArrayList(5);
    w is initied in the class constructor.
    The POJO is in the SessionBean and I would like to reference individual
    elements in the ArrayList via a value binding like so;
    #{SessionBean1.instanceOfP.w[5]}
    I'm not sure how to declare the getter/setter for member W in POJO P
    so that setter and getter injection work.

    You may not be able to directly set the indexed value.
    Try some thing like this.
    Add a property that returns the indexed value.
    Ex. if you ArrayList objets are of type "String"
    int index = 5;
    public String getMyValue(){
    return w.get[index]
    Now your value binding would look something like
    #{SessionBean1.myValue}
    BTW, if you want to access different index, create another method
    public void setIndex(int index){
    this.index = index;
    - Winston
    http://blogs.sun.com/roller/page/winston?catname=Creator

  • Please tell me how can  declare an array of object.

    how to create a two dimentional array object of a class.
    let,
    class abc{
    abc(){
    is it posible--
    abc ss=new abc[10][10]
    please tell me how can declare an array object.

    then always use String and don't consider
    StringBuffer at the outset. 'best practices' need not
    be seen as premature optimization. besides, if it is
    abstracted, does not matter how it is stored
    internallyNot sure I would agree with this example - a String is immutable, if I want to change the object then using a StringBuffer makes sense (conveys the intend, yada, yada, yada).
    Although, I do agree with you that some optimizations are best practices and should be used. I also come from the old days when optimization was always on our mind. Also, I would not expect someone to do something like re-calculate a value every time it is needed instead of storing the value in a variable, just to avoid optimization.
    I just think that the example of using a 1-dimensional array when a 2-dimentional array is a better representaion of the "real world" will both obscure the intention and compicate the code.

  • How to use multiple classes for each form

    Hi,
    I have created two forms using screen painter and now i want to use different classes for these two forms .
    I have declared the Sbo Connection in main class i.e. Set Application ,Connection Context() but while connecting to other classes
    for executing the code for that form SAP is not connected to that class.How to use multiple classes functionality i don't able to
    do that.Please provide some sample codes for that as it will be more helpful for me to understand.
    Thanks & Regards,
    Amit

    Hi Amit,
    In fact, its more advisable to use separate classes for every form that you use.  Have one common class, say, for eg., clsMain.cs which has all the connection and connectivity to other classes, wherein, the menu event and item event of this main class, will just be calling the menu / item event of other classes.
    The individual functionality of the child classes will be called from the item / menu event of the respective classes.
    Item event in clsMain.cs will be as below.
    private void oApplication_ItemEvent(string FormUID, ref SAPbouiCOM.ItemEvent pVal, out bool BubbleEvent)
                SAPbouiCOM.Form oForm;
                BubbleEvent = true;
                try
                    if ((pVal.FormTypeEx == "My_Form1Type") && (pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD))
                        oForm = oApplication.Forms.GetForm("My_FormType", pVal.FormTypeCount);
                        NameSpace.Repots.ClsForm1.ClsForm1_ItemEvent(oApplication, oCompany, oForm, ref pVal, ref BubbleEvent);
                    if ((pVal.FormTypeEx == "My_Form2Type") && (pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD))
                        oForm = oApplication.Forms.GetForm("My_FormType", pVal.FormTypeCount);
                        NameSpace.Repots.ClsForm1.ClsForm2_ItemEvent(oApplication, oCompany, oForm, ref pVal, ref BubbleEvent);
    Now, in the individual classes, you can have their respective item events, which will be called from the main class, and the respective functionalities will occur.
    Hope this helps.
    Regards,
    Satish.

  • How to determine one class is a dynamic one or not?

    hello,i got a simple question,like the title says.
    how to determine one class is a dynamic one or not?
    finally,i got an indirect solution.
    package {
    public dynamic class MyClass extends MySuperClass
    public function MyClass()
    super();
    this.isDynamic=true;
    this is a simple dynamic class,i defined a varible
    directly,it is ok with dynamic class though i didn't declare it.
    then in another class(parent class of this dynamic
    class),where i try to determine the instance of this dynamic class
    is a dynamic one or not.
    i will use one function "checkIsDynamic" to check that
    varible is exsit or not.then it will help me to determine what i
    want know.
    protected function checkIsDynamic():Boolean
    try{this["isDynamic"]}
    catch(er)
    return false;
    return true;
    if another child class of MySuperClass didn't defined this
    property,i can affirm it is not a dynamic class,or vice versa
    this function also can be expanded to another one:
    protected function checkProperty(prop:String):Boolean
    try{this[prop]}
    catch(er)
    return false;
    return true;
    it is an useful solution,defined in parent class,and to check
    the property is exist or not in child class.

    try adding a property to a class instance.

  • How to create static class in Netbeans ?

    I want to create a static class in netbeans.
    But it gives error like : static modifier not allowed here. as far as java prog concern it is syntactically correct.
    for eg.
    public static class Emp
    -------body & methods
    it looks correct syntactically, but gives error in netbeans, static modifier not allowed here. Why ? How to create static class in netbeans ?

    DrClap wrote:
    I have occasionally seen the name "static class" used to denote a class whose members are all static.I think this is quite common.
    But taking the name literally and trying to declare a class "static" is a little naive."naive" or being used to doing that in C#.

  • Help with Declaring a Class with a Method and Instantiating an Object

    hello all i am having trouble understanding and completing a lab tutorial again!
    im supposed to compile an run this code then save work to understand how to declare aclass with a method an instantiate an object of the class with the following code
    // Program 1: GradeBook.java
    // Class declaration with one method.
    public class GradeBook
    // display a welcome message to the GradeBook user
    public void displayMessage()
    System.out.println( "Welcome to the Grade Book!" );
    } // end method displayMessage
    } // end class GradeBook
    // Program 2: GradeBookTest4.java
    // Create a GradeBook object and call its displayMessage method.
    public class GradeBookTest
    // main method begins program execution
    public static void main( String args[] )
    // create a GradeBook object and assign it to myGradeBook
    GradeBook myGradeBook = new GradeBook();
    // call myGradeBook's displayMessage method
    myGradeBook.displayMessage();
    } // end main
    } // end class GradeBookTest4
    i saved above code as shown to working directory filename GradeBookTest4.java
    C:\Program Files\Java\jdk1.6.0_11\bin but recieved error message
    C:\Program Files\Java\jdk1.6.0_11\bin>javac GradeBook4a.java GradeBookTest4.java
    GradeBookTest4.java:2: class, interface, or enum expected
    ^
    GradeBookTest4.java:27: reached end of file while parsing
    ^
    2 errors
    can someone tell me where the errors are because for class or interface expected message i found a solution which says 'class? or 'interface' expected is because there is a missing { somewhere much earlier in the code. i dont know what "java:51: reached end of file while parsing " means or what to do to fix ,any ideas a re appreciated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Doesn't solve your problem, but this works for me...
    public class GradeBook
      public void displayMessage() {
        System.out.println( "Welcome to the Grade Book!" );
      public static void main( String args[] ) {
        try {
          GradeBook gradeBook = new GradeBook();
          gradeBook.displayMessage();
        } catch (Exception e) {
          e.printStackTrace();
    }

  • How do I find classes in a package

    Hi,
    I am working on an automation tool which is to be used for testing public API's in our product. The tool is supposed to work this way:
    1. A developer of the API adds a new java file containing the test code for the API in a particular package (which the tool defines). Then he compiles and places the stuff in a jar. There is also a driver class in this same package path defined by the test tool. E.g.
    driver class: com.aaa.bbb.DriverClass
    new API test file: com.aaa.bbb.TestFile
    Now the driver file's job is to find out all the other classes in this particular package and then do some processing. When I tried doing the getPackage() on this driver class to find out about the package I got back a null.
    Question 1: How can I get the package for a particular class (An ugly way to do this would be to strip it out from the classname)
    Question 2: How can I find out what other classes are there in a package?
    Thanks in advance on this.
    Nikhil Singhal
    You can also send me mails at
    [email protected]

    hai
    i have the same problem to finding the classes in package...
    in my case i know the jars name and i have loaded
    classes using code
    ResourceBundle bundle = ResourceBundle.getBundle("source\\ClasssPath");
    StringTokenizer stToke = new StringTokenizer(bundle.getString("ClassPath"),";");
    String temp;
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    while(stToke.hasMoreTokens())
         temp = stToke.nextToken().trim();
    if(temp.endsWith(".jar"))
    JarFile jar = new JarFile(new File(temp));
         Enumeration en = jar.entries();
         String pathStr;
         while(en.hasMoreElements())
         pathStr = en.nextElement().toString();
         System.out.println("pathStr ="+pathStr);
         if(pathStr.endsWith(".class"))
              System.out.println( classLoader.getResource(pathStr));
              System.out.println(classLoader.loadClass(pathStr.substring(0,pathStr.indexOf(".class")).replace('/','.').trim()));
         else classLoader.loadClass(temp);
    here i am getting the classes in that package using code
         String[] filLis = new File("//it//sella//converter//ptlf//startup//").list();
         int length = filLis.length;
         while(length-- >0)
         System.out.println(">"+filLis[length]);
    but its returnign the class when this classes in locale folder(i.e)its not getting the classes in loaded memory...
    so how to retrieve the class files names using package structure name...
    (i am having more then 20 jars files, inthat inside the jar samepackage structue may appear in more then one jars )
    pls help me in this field..
    Thanx

  • How to declare a list of dates

    Hi,
    I have an item which type is "Display as text based on LOV". I put in the source section under the type "Pl/SQL function body" the following pl/sql function :
    DECLARE
    X VARCHAR2 (4000);
    Y DATE ;
    BEGIN
    X := 'SELECT distinct(TO_CHAR(DATE1, ''YYYY'')) d, (TO_CHAR(DATE1, ''YYYY'')) r FROM SIVOA.EVV_'|| :p4_site ||' WHERE CLEF_VAR = (SELECT CLEF_VAR FROM SIVOA.SITE_DEBIT_RIVIERE WHERE SITE ='''|| :p4_site ||''')
    order by d';
    EXECUTE IMMEDIATE X INTO Y;
    RETURN Y ;
    END;The problem is that I get an ORA error.
    ORA-00932: types de données incohérents ; attendu : - ; obtenu : -
    I know that I have declared Y as a date and that what is returned by my function is a list of dates. I don't know how to declare a list of dates or whatever to be returned as a lis of values. Hope I am clear, sorry for my english.
    Thank you for your kind help.
    Christian

    Hi Tony
    You hare very patient with me thank you !!!
    Let me clarify well.
    I am trying to create a list of values based on dates contained in a table. This list of values should contains the "years". If the table contains data for the years 2005, 2006, 2007, then the list of value should return :
    2006
    2007
    2008
    As I want a list of value I need to have a display and a return value. The name of the table is 'dynamic' It is the item P4_SITE that contains a part of the name of the table. This is why I am usins PL/SQL, because I don't know the name of the table in advance.
    I have not seen any way to put a pl/sql statement in the List of values definition of the item. Thi s is why I try to make a LOV with the SOURCE of the item.
    Hope I am clear.

Maybe you are looking for

  • ANY IDEAS FOR THIS PROB

    THIS IS AS FAR AS I GOT - PROBLEM IS ON THE BOTTOM import javax.swing.JOptionPane; public class Rec public static void main (String args[])      private String strLen;      private String strWid;      private float fltLen = 1;      private float fltL

  • Adobe photoshop CC 2014 crashes

    I downloaded the Adobe Photoshop CC 2014 - but only for 30 days... And I was so excited! But everytime I start my photoshop, it crashes after 2-5 minutes! And my computer can't tell me a reason!? Can anyone help me? I tried uninstall it and reinstall

  • Is there anyway to add a border around a PDF page

    Hello, Is there anyway to add a 1pt black border around every Page in a Acrobat Document? Thanks! babs

  • Welcome page script problem

    When SAP start, the welcome page become with script errors. How to solve it ?

  • Reg : mail step in wf

    hi , In my workflow..when ever quotation is created.(suppose USER1 has created quotation)...... Workflow starts  and there is an activity with task and rule in task. The rule finds the responible agent and sends the work item to that ID (suppose USER