How to execute a static method twice

Hi all,
In the attached code, as you can see I call the method at.sendRequestString(), twice from main() method.
The first line in sendRequestString() method is Authenticator.setDefault(new MyAuthenticator());
Authenticator is an abstract class and setDefault is a static method in that class.
When I call sendRequestString() for the second time, Authenticator.setDefault(new MyAuthenticator()); is not executed. ie; Authenticator.setDefault gets executed once and only once.
Does this happen because that Authenticator.setDefault is a static method and it will be executed only once?
If yes, how can I make it work for the second time?
Here is my simple Java code. The username and password given in the code are just sample ones.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
public class GetAuthenticatedData
     public String address;
     static String username;
     static String password;
     public GetAuthenticatedData(String address){
          this.address = address;
     public String sendRequestString()
          Authenticator.setDefault(new MyAuthenticator());//BEING STATIC METHOD, SET DEFAULT CALLED ONLY ONCE
         String str = null;
         try {
             URL url = new URL(address);
             BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
             while (( str = in.readLine()) != null) {
                  return str;
             in.close();
         } catch (MalformedURLException e) {
              System.out.println("e1"+e);
         } catch (IOException e) {
              System.out.println("e2"+e);
         Authenticator.setDefault(null);
          return str;
     public static void main(String args[]){
          username = "username1";
          password = "password1";
          GetAuthenticatedData at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
          System.out.println("value corresponding to username1 and password1"+at.sendRequestString());
          username = "username2";
          password = "password2";
          at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
          System.out.println("value corresponding to username2 and password2 "+at.sendRequestString());
class MyAuthenticator extends Authenticator {
     public MyAuthenticator(){
          getPasswordAuthentication();
          protected PasswordAuthentication getPasswordAuthentication() {
               PasswordAuthentication auth = new PasswordAuthentication(GetAuthenticatedData.username, GetAuthenticatedData.password.toCharArray());
             System.out.println("Username"+auth.getUserName());
             System.out.println("Password"+new String(auth.getPassword()));
               return auth;
}Please help with an appropriate solution.
Any help in this regard will be well appreciated with dukes.
Anees

Thanks for your valuable help Looce. But it still does not solve the problem.
Here is how I used your code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
public class GetAuthenticatedData
     public String address;
     static String username;
     static String password;
     public GetAuthenticatedData(String address){
          this.address = address;
     MyAuthenticator authenticator = new MyAuthenticator("username1","password1".toCharArray());
     public String sendRequestString(String user, String pass)
          authenticator.setUsername(user);
          authenticator.setPassword(pass.toCharArray());
          Authenticator.setDefault(authenticator);
         String str = null;
         try {
             URL url = new URL(address);
             BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
             while (( str = in.readLine()) != null) {
                  return str;
             in.close();
         } catch (MalformedURLException e) {
              System.out.println("e1"+e);
         } catch (IOException e) {
              System.out.println("e2"+e);
         Authenticator.setDefault(null);
          return str;
     public static void main(String args[]){
          username = "username1";
          password = "password1";
          GetAuthenticatedData at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
          System.out.println("value corresponding to username1 and password1"+at.sendRequestString("username1","password1"));
          username = "username2";
          password = "password2";
          at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
          System.out.println("value corresponding to username2 and password2 "+at.sendRequestString("password2","password2"));
* This class implements an Authenticator whose username and password information can
* change over time.
* @author Cynthia G., Sun Java forums: http://forums.sun.com/thread.jspa?messageID=10504183
class MyAuthenticator extends java.net.Authenticator {
  /** Stored user name. */
  private String username;
  /** Stored password. */
  private char[] password;
  /** Constructs an instance of MyAuthenticator with the given initial user name
   * and password. These may be modified with the setUsername and setPassword
   * methods.
  public MyAuthenticator(String username, char[] password) {
    this.username = username;
    this.password = password;
  public void setUsername(String username) { this.username = username; }
  public void setPassword(char[] password) { this.password = password; }
  protected java.net.PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }
}

Similar Messages

  • How to call a static method from an event handler

    Hi,
       I'm trying to call a static method of class I designed.  But I don't know how to do it.  This method will be called from an event handler of a web dynpro for Abap application.
    Can somebody help me?
    Thx in advance.
    Hamza.

    To clearly specify the problem.
    I have a big part code that I use many times in my applications. So I decided to put it in a static method to reuse the code.  but my method calls functions module of HR module.  but just after the declaration ( at the first line of the call function) it thows an exception.  So I can't call my method.

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • How to execute a Java method when row inserted into a database table?

    I have the need to fire off a java method when a row is inserted into a database table. I am unfortunately working with MySQL which just recently supported triggers but these new triggers can not execute a Java application on any event.
    What I am looking for is an event driven approach such that when a row is inserted into a specific table I can fire off a java method (sitting in a tomcat container) that will take the contents and send it to a web service.
    It has been mentioned that JMS may have the ability to poll and monitor a database table. Just wondering if anyone could point me in the right direction.
    thanks
    JavaTek

    A service handler might be the right way to run some code at the end of a service call (another way would be to make use of filters).
    First, make sure your static table is merged with ServiceHandlers.
    Secondary, change your custom method name into one that is not already in the service definition of COLLECTION_COPY_LOT (preferably a unique method name like collectionCopyLotLastAction that describes its purpose) and remove the following line from your code:
    m_service.doCodeEx("",this);Now create a service definition for COLLECTION_COPY_LOT in your custom component based on the original COLLECTION_COPY_LOT (copy paste from the original service definition) and add you own method collectionCopyLotLastAction as the last step in the service. Play with the load order to make sure CS is using your service definition of COLLECTION_COPY_LOT instead of the original.
    regards,
    Fabian

  • How to call a static method of a class (continued)

    In reference to the above topic posted one week ago I give you the relative code. The problem is resolved and it was the following one (amazing for me since I looked for any possible error in the code like the one posted in my article but I could never imagine this trivial thing.........):
    the package name which is the directory with the appropriate class files should not extend the lenght of 8 characters!!! Initially I had a package named Applications (too long for DOS...) and when I renamed it to Test everything worked. Any suggestion on how to overcome this DOS filesystem problem?
    Christos
    Here is my simplified code
         package test;
         import java.io.*;
         import java.net.URL;
         import javax.swing.*;
         import java.beans.*;
         import java.awt.*;
         import java.awt.event.*;
         public class myapplet extends JApplet
         private MyClass myframe;
         private JDesktopPane desktop;
         private Dimension d;
    public void init() {
    myframe= new MyClass();
    desktop = new JDesktopPane();
    d=desktop.getSize();
    try {
    javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
    createGUI();
    } catch (Exception e) {
    System.err.println("createGUI didn't successfully complete");
         private void createGUI() {
         myframe.pack();
         myframe.setBounds(0,0,d.width,d.height);
         desktop.add(myframe);
         this.getContentPane().add(desktop);
         try {
         myframe.setMaximum(true);
         } catch (PropertyVetoException e) {
         e.printStackTrace();
         myframe.setVisible(true);
    protected static ImageIcon createAppletImageIcon(String path,
    String description)
    int MAX_IMAGE_SIZE = 75000; //Change this to the size of
    //your biggest image, in bytes.
    int count = 0;
    BufferedInputStream imgStream = new BufferedInputStream(
    myapplet.class.getResourceAsStream(path));
    if (imgStream != null)
    byte buf[] = new byte[MAX_IMAGE_SIZE];
    try {
    count = imgStream.read(buf);
    } catch (IOException ieo) {
    System.err.println("Couldn't read stream from file: " + path);
    try {
    imgStream.close();
    } catch (IOException ieo) {
    System.err.println("Can't close file " + path);
    if (count <= 0) {
    System.err.println("Empty file: " + path);
    return null;
    return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf),
    description);
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    followed by the class MyClass
    package test;
         import javax.swing.*;
         import java.awt.*;
         import java.awt.event.*;
         public class MyClass extends JInternalFrame
         private JLabel jl;
         private String myicon1="images/myimage.gif";
         private ImageIcon image1;
         public MyClass()
         super ( "This is my application",false,true,true,false);
         setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    image1= myapplet.createAppletImageIcon(myicon1,"");
    jl = new JLabel("This is my image",
              image1,JLabel.CENTER);
    jl.setFont (new Font("Times-Roman",Font.BOLD, 17));
    getContentPane().add(jl);
    and finally the html file with the applet tag:
    <APPLET CODE = "test.myapplet" width=760 height=380>
    </APPLET>

    I have to say that everything works fine even with
    long package names besides the loading of the image in
    MyClass (in fact you see the JInternalFrame with the
    JLabel without icon!). Since I never saw an error in
    the Sun Java Console or the DOS window I tried this
    last solution, i.e. to shorten the package name. Only
    then the icon appears in the label......strange thingsThere shouldn't be a problem with long package (and hence long directory) names.
    private String myicon1="images/myimage.gif"; // which becomes the 'path' variable below
    BufferedInputStream imgStream = new BufferedInputStream(
    myapplet.class.getResourceAsStream(path));So are you sure you are always putting this images subdirectory underneath where your myapplet class lives? If myapplet.class lives in /foo/bar/mypackage, belongs to the 'mypackage' package, and your classpath includes /foo/bar, then your gif file better be at /foo/bar/mypackage/images/myimage.gif (or actually at mypackage/images/myimage.gif from any classpath root)

  • How to call a static method of a class from another class?

    Hello,
    I have two classes in a package. The first one
    package my package;
    public class class1
    protected static ImageIcon createIcon(String path)
    The second one
    package my package;
    public class class2
    private ImageIcon image1;
    image1 = class1.createIcon("/mypath");
    This does not work since class2 cannot load the appropriate image. Where do I have to define the ImageIcon variables in class one or two and do they have to be static variables?
    Thanks in advance
    Christos

    If the two classes are in the same package, that will work, in fact. A trivial example:
    package foo;
    public class Foo1 {
         protected static String getString() {
              return "World";
    // Note: Member of the same package
    package foo;
    public class Foo2 {
         public static void main(String[] argv) {
              System.out.println("Hello "+ foo.Foo1.getString());
    }However, if they are in different packages that won't work - the protected keyword guarantees that only classes derived from the class with the protected method can access it: Therefore this will not work:
    package foo;
    public class Foo1 {
         protected static String getString() {
              return "World";
    package foo.bar;
    public class Foo2{
         public static void main(String[] argv) {
              System.out.println("Hello "+ foo.Foo1.getString());
    }But this will:
    package foo;
    public class Foo1 {
         protected static String getString() {
              return "World";
    package foo.bar;
    public class Foo2 extends foo.Foo1 {
         public static void main(String[] argv) {
              System.out.println("Hello "+ foo.Foo1.getString());
    }I think you should read up a bit more about packages and inheritance, because you're going to have a lot of trouble without a good understanding of both. Try simple examples first, like the above, and if you hit problems try to produce a simple test case to help you understand the problem rather than trying to debug your whole application.
    Dave.

  • How to access a static method inside the JSP page

    Here i had wrote the code in java to access databases , i had include the class path to all the class files.
    my problem is when i click the register.jsp page, it will pose eror as null pointer exception i've put my code in this section as follows
    memberchecking.jsp
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,businessclasses.*,businessobjects.*,projectutils.DateUtilities.*,java.util.*" errorPage="" %>
    <html>
    <head>
    <title>Checking Member's Registration Details...</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <%
    String loginId = request.getParameter("loginId");
    String resourcePassword = request.getParameter("resourcePassword");
    String confirmPassword = request.getParameter("confirmPassword");
    String resourceStatus=request.getParameter("resourceStatus");
    String nameTitle = request.getParameter("nameTitle");
    String jobTitle = request.getParameter("jobTitle");
    String firstName = request.getParameter("firstName");
    String middleName = request.getParameter("middleName");
    String lastName = request.getParameter("lastName");
    String displayName = request.getParameter("displayName");
    String resourceInitials = request.getParameter("resourceIniitials");
    String countryCode = request.getParameter("countryCode");
    String resourceLanguage = request.getParameter("resourceLanguage");
    //String resourceCurrency = request.getParameter("resourceCurrency");
    String resourceEmail2 = request.getParameter("resourceEmail2");
    String birthMonth = request.getParameter("birthMonth");
    String birthDay = request.getParameter("birthDay");
    String birthYear = request.getParameter("birthYear");
    String resourceGender = request.getParameter("resourceGender");
    String martialStatus = request.getParameter("martialStatus");
    String resourceOccupation = request.getParameter("resourceOccupation");
    String webPage = request.getParameter("webPage");
    String homePhone = request.getParameter("homePhone");
    String homePhone2 = request.getParameter("homephone2");
    String homeFax = request.getParameter("homepFax");
    String phoneOffice = request.getParameter("phoneOffice");
    String phoneOffice2 = request.getParameter("phoneOffice2");
    String officeFax = request.getParameter("officeFax");
    String resourcePager = request.getParameter("resourcePager");
    String resourceMobile = request.getParameter("resourceMobile");
    String resourceType=request.getParameter("resourceType");
    String resourceName = firstName + " " + middleName + " " + lastName;
    //java.util.Date resourceBirthDate = (String)birthMonth + "/" + birthDay + "/" + birthYear;
    session.setAttribute("Name",resourceName);
    session.setAttribute("UserId",loginId);
    out.println("name==========="+resourceName);
    //check whether the input data is valid for insert
    //input validation code goes here.....
    ResourceBC aResourceBC=new ResourceBC();
    //marshall the resource
    ResourceBO resource=new ResourceBO();
    String e1 = (String)resource.getEmail();
    String e2 = (String)resource.getEmail2();
    if(loginId != e1 && resourceEmail2 != e2 ) {
              resource.setStatus( "L");
              resource.setId(5);
              resource.setCountryCode(countryCode);
         //     resource.setResourceTypeCode(resourceType);     
         //     resource.setResourceParent(rs.getLong(6));
         //     resource.setHKey(rs.getLong(7));          
              resource.setName(resourceName);
              resource.setDisplayName(displayName);
              resource.setLogonPassword(resourcePassword);
              resource.setNameTitle(nameTitle);
              resource.setJobTitle(jobTitle);
              resource.setEmail(loginId);
              resource.setEmail2(resourceEmail2);          
         //     resource.setPasswordUpdateDate(rs.getDate(14));
         //     resource.setPasswordExpireDate(rs.getDate(15));
         //     resource.setAccessCode(rs.getString(16));
         //     resource.setLogonUnSuccessTries(0);
              resource.setWebPage(webPage);
              resource.setPhoneOffice(phoneOffice);
              resource.setPhoneOffice2(phoneOffice2);
              resource.setPhoneOfficeFax(officeFax);
              resource.setPhoneHome(homePhone);
              resource.setPhoneHome2(homePhone2);
              resource.setPhoneHomeFax(homeFax);
              resource.setMobile(resourceMobile);
              resource.setPager(resourcePager);
              resource.setStatus(resourceStatus);     
              resource.setGender(resourceGender);     
         //     resource.setBirthDate(resourceBirthDate);
              resource.setMartialStatus(martialStatus);
              resource.setLanguage(resourceLanguage);
    //          resource.setCurrency(resourceCurrency);
    //          resource.setPhoto(photo);
              resource.setInitials(resourceInitials);                         
    //          resource.setCreatedBy(1);
    //          resource.setCreatedDate(rs.getDate(36));
    //          resource.setUpdatedBy(rs.getLong(37));
    //          resource.setUpdatedDate(rs.getDate(38));
              resource.setFirstName(firstName);
              resource.setLastName(lastName);
              resource.setMiddleName(middleName);     
              //resource.setCreatedDate(new java.sql.Date());
              int rowsAdded=aResourceBC.resourceAdd(resource);
              out.println("rowsAdded= "+rowsAdded);
              //add message for success or failure to add resource
              String msg="";
              if(rowsAdded == -1){
                   msg="<font color=red>The ResourceName already exists .Try another</font>";
                   session.setAttribute("message",msg);
                   response.sendRedirect(response.encodeRedirectURL("memberregister.jsp"));
              else if(rowsAdded > 0){
                   msg="<font color=green>Resource Added successfully..........</font>";     
                   session.setAttribute("message",msg);
    %>
                   <jsp:forward page="memberlist.jsp">
                   <jsp:param name="message" value="<%=msg%>"/>
                   </jsp:forward>
    <%}
    %>
    </body>
    </html>
    ResourceBC.java
    package businessclasses;
    import java.sql.*;
    import businessobjects.ResourceBO;
    import java.util.*;
    import dbutilities.DBManager;
    public class ResourceBC
         public Vector resourceList() throws Exception{
         Vector resourceList=new Vector();
         String listSQL="";
         StringBuffer listSQLBuffer=new StringBuffer();
         listSQLBuffer.append("SELECT ");
         listSQLBuffer.append("RES_ID,");
         listSQLBuffer.append("RES_NAME,");
         listSQLBuffer.append("CNTRY_CODE,");
         listSQLBuffer.append("RES_LOGON_PASSWORD,");
         listSQLBuffer.append("RESTYPE_CODE,");
         listSQLBuffer.append("RES_PARENT,");
         listSQLBuffer.append("RES_HKEY,");
         listSQLBuffer.append("RES_DISPLAY_NAME,");
         listSQLBuffer.append("RES_NAME_TITLE,");     
         listSQLBuffer.append("RES_JOB_TITLE,");     
         listSQLBuffer.append("RES_EMAIL,");
         listSQLBuffer.append("RES_EMAIL2,");     
         listSQLBuffer.append("RES_PASSWORD_ACTION,");     
         listSQLBuffer.append("RES_PASSWORD_UPDATE_DATE,");     
         listSQLBuffer.append("RES_PASSWORD_EXPIRE_DATE,");     
         listSQLBuffer.append("RES_ACCESS_CODE,");     
         listSQLBuffer.append("RES_LOGON_UNSUCCESS_TRIES,");     
         listSQLBuffer.append("RES_WEB_PAGE,");
         listSQLBuffer.append("RES_PHONE_OFFICE,");
         listSQLBuffer.append("RES_PHONE_OFFICE2,");
         listSQLBuffer.append("RES_PHONE_OFFICE_FAX,");
         listSQLBuffer.append("RES_PHONE_HOME,");
         listSQLBuffer.append("RES_PHONE_HOME2,");
         listSQLBuffer.append("RES_PHONE_HOME_FAX,");
         listSQLBuffer.append("RES_MOBILE,");
         listSQLBuffer.append("RES_PAGER,");
         listSQLBuffer.append("RES_STATUS,");
         listSQLBuffer.append("RES_GENDER,");
         listSQLBuffer.append("RES_BIRTH_DATE,");
         listSQLBuffer.append("RES_MARTIAL_STATUS,");
         listSQLBuffer.append("RES_LANGUAGE,");
         listSQLBuffer.append("RES_CURRENCY,");
         listSQLBuffer.append("RES_PHOTO,");
         listSQLBuffer.append("RES_CREATED_BY,");
         listSQLBuffer.append("RES_NAME_INITIALS,");          
         listSQLBuffer.append("RES_CREATED_DATE,");
         listSQLBuffer.append("RES_UPDATED_BY");
         listSQLBuffer.append("RES_UPDATED_DATE,");
         listSQLBuffer.append("RES_NAME_FIRST,");
         listSQLBuffer.append("RES_NAME_LAST,");
         listSQLBuffer.append("RES_NAME_MIDDLE");     
         listSQLBuffer.append(" FROM T_RESOURCES ");
         listSQL=listSQLBuffer.toString();
    System.out.println("listSQL---"+listSQL);
         DBManager dbManager=new DBManager();
         Connection con =dbManager.getConnection();
         Statement stmt=con.createStatement();
         ResultSet rs=stmt.executeQuery(listSQL);
         ResourceBO resource=null;
         while(rs.next()){
              resource=new ResourceBO();
              resource.setId(rs.getLong(1));
              resource.setName(rs.getString(2));
              resource.setCountryCode(rs.getString(3));
              resource.setLogonPassword(rs.getString(4));
              resource.setResourceTypeCode(rs.getLong(5));     
              resource.setResourceParent(rs.getLong(6));
              resource.setHKey(rs.getLong(7));          
              resource.setDisplayName(rs.getString(8));
              resource.setNameTitle(rs.getString(9));
              resource.setJobTitle(rs.getString(10));
              resource.setEmail(rs.getString(11));
              resource.setEmail2(rs.getString(12));          
              resource.setPasswordAction(rs.getString(13));
              resource.setPasswordUpdateDate(rs.getDate(14));
              resource.setPasswordExpireDate(rs.getDate(15));
              resource.setAccessCode(rs.getString(16));
              resource.setLogonUnSuccessTries(rs.getLong(17));
              resource.setWebPage(rs.getString(18));
              resource.setPhoneOffice(rs.getString(19));
              resource.setPhoneOffice2(rs.getString(20));
              resource.setPhoneOfficeFax(rs.getString(21));
              resource.setPhoneHome(rs.getString(22));
              resource.setPhoneHome2(rs.getString(23));
              resource.setPhoneHomeFax(rs.getString(24));
              resource.setMobile(rs.getString(25));
              resource.setPager(rs.getString(26));
              resource.setStatus(rs.getString(27));     
              resource.setGender(rs.getString(28));     
              resource.setBirthDate(rs.getDate(29));
              resource.setMartialStatus(rs.getString(30));
              resource.setLanguage(rs.getString(31));
              resource.setCurrency(rs.getString(32));
              resource.setPhoto(rs.getString(33));
              resource.setCreatedBy(rs.getLong(34));
              resource.setInitials(rs.getString(35));                         
              resource.setCreatedDate(rs.getDate(36));
              resource.setUpdatedBy(rs.getLong(37));
              resource.setUpdatedDate(rs.getDate(38));
              resource.setFirstName(rs.getString(39));
              resource.setLastName(rs.getString(40));
              resource.setMiddleName(rs.getString(41));          
              resourceList.add(resource);
              con.close();
              con=null;
              return resourceList;
    //Method to insert the values into the database
    public int resourceAdd(ResourceBO resource){
         System.out.println("in resourceAdd method ");
         //check for duplicate record in the table
         String checkDuplicationSQL="SELECT RES_ID FROM T_RESOURCES WHERE RES_ID='"+resource.getId()+"'";     
         DBManager dbManager=new DBManager();//.getInstance();
         boolean hasDuplicateRecord=dbManager.hasDuplicateRecord(checkDuplicationSQL);
         int rowsAdded=0;
         //insert the record
         //hasDuplicateRecord=false;
              if(!hasDuplicateRecord){
                   //get the next resource id for insertion
              long nextID=dbManager.getNextIDForColumnAndTable("RES_ID","T_RESOURCES");
              System.out.println("nextID================== "+nextID);
    StringBuffer fieldsbuffer=new StringBuffer();
         fieldsbuffer.append("INSERT INTO T_RESOURCES (");
         fieldsbuffer.append("RES_ID,");
         fieldsbuffer.append("RES_NAME,");
         fieldsbuffer.append("CNTRY_CODE,");
         fieldsbuffer.append("RES_LOGON_PASSWORD,");
         fieldsbuffer.append("RESTYPE_CODE,");     
         fieldsbuffer.append("RES_PARENT,");
         fieldsbuffer.append("RES_HKEY,");
         fieldsbuffer.append("RES_DISPLAY_NAME,");     
         fieldsbuffer.append("RES_NAME_TITLE,");
         fieldsbuffer.append("RES_JOB_TITLE,");
         fieldsbuffer.append("RES_EMAIL,");
         fieldsbuffer.append("RES_EMAIL2,");
         fieldsbuffer.append("RES_PASSWORD_ACTION,");
         fieldsbuffer.append("RES_PASSWORD_UPDATE_DATE,");          
         fieldsbuffer.append("RES_PASSWORD_EXPIRE_DATE,");          
         fieldsbuffer.append("RES_ACCESS_CODE,");          
         fieldsbuffer.append("RES_LOGON_UNSUCCESS_TRIES,");     
         fieldsbuffer.append("RES_WEB_PAGE,");
         fieldsbuffer.append("RES_PHONE_OFFICE,");
         fieldsbuffer.append("RES_PHONE_OFFICE2,");
         fieldsbuffer.append("RES_PHONE_OFFICE_FAX,");
         fieldsbuffer.append("RES_PHONE_HOME,");
         fieldsbuffer.append("RES_PHONE_HOME2,");
         fieldsbuffer.append("RES_PHONE_HOME_FAX,");
         fieldsbuffer.append("RES_MOBILE,");
         fieldsbuffer.append("RES_PAGER,");
         fieldsbuffer.append("RES_STATUS,");     
         fieldsbuffer.append("RES_GENDER,");     
         fieldsbuffer.append("RES_BIRTH_DATE,");          
         fieldsbuffer.append("RES_MARTIAL_STATUS,");          
         fieldsbuffer.append("RES_LANGUAGE,");          
         fieldsbuffer.append("RES_CURRENCY,");          
         fieldsbuffer.append("RES_PHOTO,");     
    /*     fieldBuffer.append("RES_CREATED_BY,");
         fieldBuffer.append("RES_NAME_INITIALS,");          
         fieldBuffer.append("RES_CREATED_DATE,");
         fieldBuffer.append("RES_UPDATED_BY");
         fieldBuffer.append("RES_UPDATED_DATE,");
         fieldBuffer.append("RES_NAME_FIRST,");
         fieldBuffer.append("RES_NAME_LAST,");
         fieldBuffer.append("RES_NAME_MIDDLE");     */
         StringBuffer valuesBuffer=new StringBuffer(" VALUES(");
    valuesBuffer.append(nextID+",");
         valuesBuffer.append("'"+resource.getName()+",");
         valuesBuffer.append("'"+resource.getCountryCode()+",");
         valuesBuffer.append("'"+resource.getLogonPassword()+"',");
         valuesBuffer.append("'"+resource.getResourceTypeCode()+",");
         valuesBuffer.append("'"+resource.getResourceParent()+",");
         valuesBuffer.append("'"+resource.getHKey()+",");
         valuesBuffer.append("'"+resource.getDisplayName()+",");
         valuesBuffer.append("'"+resource.getNameTitle()+",");
         valuesBuffer.append("'"+resource.getJobTitle()+",");
         valuesBuffer.append("'"+resource.getEmail()+"',");
         valuesBuffer.append("'"+resource.getEmail2()+"',");
         valuesBuffer.append("'"+resource.getPasswordAction()+",");
         valuesBuffer.append("'"+resource.getPasswordUpdateDate()+",");
         valuesBuffer.append("'"+resource.getPasswordExpireDate()+",");
         valuesBuffer.append("'"+resource.getAccessCode()+",");
         valuesBuffer.append("'"+resource.getLogonUnsuccessTries()+",");     
         valuesBuffer.append("'"+resource.getWebPage()+"',");
         valuesBuffer.append("'"+resource.getPhoneOffice()+"',");
         valuesBuffer.append("'"+resource.getPhoneOffice2()+"',");
         valuesBuffer.append("'"+resource.getPhoneOfficeFax()+"',");
         valuesBuffer.append("'"+resource.getPhoneHome()+"',");
         valuesBuffer.append("'"+resource.getPhoneHome2()+"',");
         valuesBuffer.append("'"+resource.getPhoneHomeFax()+"',");
         valuesBuffer.append("'"+resource.getMobile()+"',");
         valuesBuffer.append("'"+resource.getPager()+"',");
         valuesBuffer.append("'"+resource.getStatus()+"',");
         valuesBuffer.append("'"+resource.getGender()+"',");
         valuesBuffer.append("'"+resource.getBirthDate()+"',");
         valuesBuffer.append("'"+resource.getMartialStatus()+"',");
         valuesBuffer.append("'"+resource.getLanguage()+"',");
         valuesBuffer.append("'"+resource.getCurrency()+"',");
         valuesBuffer.append("'"+resource.getPhoto()+"',");
         valuesBuffer.append("'"+resource.getCreatedBy()+"',");
         valuesBuffer.append("'"+resource.getInitials()+"',");
         valuesBuffer.append("'"+resource.getCreatedDate()+"',");
         valuesBuffer.append("'"+resource.getUpdatedBy()+"',");
         valuesBuffer.append("'"+resource.getUpdatedDate()+"',");
         valuesBuffer.append("'"+resource.getFirstName()+"',");
         valuesBuffer.append("'"+resource.getLastName()+"',");
         valuesBuffer.append("'"+resource.getMiddleName()+"')");
         String insertSQL=fieldsbuffer.toString()+valuesBuffer.toString();
              System.out.println("insertSQL="+insertSQL);
              rowsAdded=dbManager.executeSQL(insertSQL);
              System.out.println("rowsAdded= "+rowsAdded+"hasDuplicateRecord "+hasDuplicateRecord);
              }//end if
              else{
                   //throw new Exception("Has a duplicate Record");
                   return -1;
              return rowsAdded;
    public int resourceUpdate(ResourceBO resource){
              int rowsUpdated=0;
    /*          String orgCodeStr=null;
              if(resource.getOrgCode()==0){
                   orgCodeStr="NULL";
         }else{
                   orgCodeStr=""+resource.getOrgCode();
              StringBuffer updateSQLBuffer=new StringBuffer();
         updateSQLBuffer.append("UPDATE T_RESOURCES SET ");          
         updateSQLBuffer.append("RES_NAME='"+resource.getName()+"',");
         updateSQLBuffer.append("CNTRY_CODE='"+resource.getCountryCode()+"',");
         updateSQLBuffer.append("RES_LOGON_PASSWORD='"+resource.getLogonPassword()+"',");
         updateSQLBuffer.append("RESTYPE_CODE="+resource.getResourceTypeCode()+",");
         updateSQLBuffer.append("RES_PARENT="+resource.getResourceParent()+",");
         updateSQLBuffer.append("RES_HKEY="+resource.getHKey()+",");
         updateSQLBuffer.append("RES_DISPLAY_NAME="+resource.getDisplayName()+",");
         updateSQLBuffer.append("RES_NAME_TITLE="+resource.getNameTitle()+",");
         updateSQLBuffer.append("RES_JOB_TITLE="+resource.getJobTitle()+",");
         updateSQLBuffer.append("RES_EMAIL='"+resource.getEmail()+"',");
         updateSQLBuffer.append("RES_EMAIL2='"+resource.getEmail2()+"',");
         updateSQLBuffer.append("RES_PASSWORD_ACTION="+resource.getPasswordAction()+",");
         updateSQLBuffer.append("RES_PASSWORD_UPDATE_DATE="+resource.getPasswordUpdateDate()+",");
         updateSQLBuffer.append("RES_PASSWORD_EXPIRE_DATE="+resource.getPasswordExpireDate()+",");
         updateSQLBuffer.append("RES_ACCESS_CODE="+resource.getAccessCode()+",");
         updateSQLBuffer.append("RES_LOGON_UNSUCCESS_TRIES="+resource.getLogonUnsuccessTries()+",");     
         updateSQLBuffer.append("RES_WEB_PAGE='"+resource.getWebPage()+"',");
         updateSQLBuffer.append("RES_PHONE_OFFICE='"+resource.getPhoneOffice()+"',");
         updateSQLBuffer.append("RES_PHONE_OFFICE2='"+resource.getPhoneOffice2()+"',");
         updateSQLBuffer.append("RES_PHONE_OFFICE_FAX='"+resource.getPhoneOfficeFax()+"',");
         updateSQLBuffer.append("RES_PHONE_HOME='"+resource.getPhoneHome()+"',");
         updateSQLBuffer.append("RES_PHONE_HOME2='"+resource.getPhoneHome2()+"',");
         updateSQLBuffer.append("RES_PHONE_HOME_FAX='"+resource.getPhoneHomeFax()+"',");
         updateSQLBuffer.append("RES_MOBILE='"+resource.getMobile()+"',");
         updateSQLBuffer.append("RES_PAGER='"+resource.getPager()+"',");
         updateSQLBuffer.append("RES_STATUS='"+resource.getStatus()+"',");
         updateSQLBuffer.append("RES_GENDER='"+resource.getGender()+"',");
         updateSQLBuffer.append("RES_BIRTH_DATE='"+resource.getBirthDate()+"',");
         updateSQLBuffer.append("RES_MARTIAL_STATUS='"+resource.getMartialStatus()+"',");
         updateSQLBuffer.append("RES_LANGUAGE='"+resource.getLanguage()+"',");
         updateSQLBuffer.append("RES_CURRENCY='"+resource.getCurrency()+"',");
         updateSQLBuffer.append("RES_PHOTO='"+resource.getPhoto()+"',");
         updateSQLBuffer.append("RES_NAME_INITIALS='"+resource.getInitials()+"',");
         updateSQLBuffer.append("RES_NAME_FIRST='"+resource.getFirstName()+"',");
         updateSQLBuffer.append("RES_NAME_LAST='"+resource.getLastName()+"',");
         updateSQLBuffer.append("RES_NAME_MIDDLE='"+resource.getMiddleName()+"'");
         updateSQLBuffer.append("WHERE RES_ID="+resource.getId());
         String updateSQL=updateSQLBuffer.toString();
              //String updateSQL="UPDATE T_RESOURCES SET CLIENT_NAME='"+resource.getName()+"',CLIENT_STATUS='"+resource.getStatus()+"',CLIENT_EMAIL_PRIMARY='"+resource.getEmailPrimary()+"',CLIENT_EMAIL_ALTERNATIVE='"+resource.getEmailAlternate()+"',CLIENT_CURRENCY_SYMBOL='"+resource.getCurrencySymbol()+"',CLIENT_CURRENCY_DIGITS="+resource.getCurrencyDigits()+",CLIENT_DIRECTORY_DOCUMENT='"+resource.getDirectoryDocument()+"',CLIENT_DIRECTORY_TEMPLATE='"+resource.getDirectoryTemplate()+"',CLIENT_STORAGE_QUOTA="+resource.getStorageQuota()+",CLIENT_KEY='"+resource.getKey()+"' WHERE CLIENT_ID="+resource.getId();
              System.out.println("updateSQL---"+updateSQL);
              DBManager dbManager=new DBManager();
              rowsUpdated=dbManager.executeSQL(updateSQL);
              return rowsUpdated;
    public int resourceDelete(long resourceId){
              int rowsDeleted=0;
              DBManager dbManager=new DBManager();
              String deleteSQL="DELETE FROM T_RESOURCES WHERE RES_ID="+resourceId;
              System.out.println("deleteSQL==="+deleteSQL);
              rowsDeleted=dbManager.executeSQL(deleteSQL);
              System.out.println("rowsDeleted= "+rowsDeleted);
              return rowsDeleted;
    public ResourceBO getResourceById(long resourceId)throws Exception{
              StringBuffer selectSQLBuffer=new StringBuffer();
              selectSQLBuffer.append("SELECT ");
              selectSQLBuffer.append("RES_ID,");
              selectSQLBuffer.append("RES_NAME,");
              selectSQLBuffer.append("CNTRY_CODE,");
              selectSQLBuffer.append("RES_LOGON_PASSWORD,");
              selectSQLBuffer.append("RESTYPE_CODE,");
              selectSQLBuffer.append("RES_PARENT,");
              selectSQLBuffer.append("RES_HKEY,");
              selectSQLBuffer.append("RES_DISPLAY_NAME,");
              selectSQLBuffer.append("RES_NAME_TITLE,");          
              selectSQLBuffer.append("RES_JOB_TITLE,");     
              selectSQLBuffer.append("RES_EMAIL,");
              selectSQLBuffer.append("RES_EMAIL2,");     
              selectSQLBuffer.append("RES_PASSWORD_ACTION,");     
              selectSQLBuffer.append("RES_PASSWORD_UPDATE_DATE,");     
              selectSQLBuffer.append("RES_PASSWORD_EXPIRE_DATE,");     
              selectSQLBuffer.append("RES_ACCESS_CODE,");     
              selectSQLBuffer.append("RES_LOGON_UNSUCCESS_TRIES,");     
              selectSQLBuffer.append("RES_WEB_PAGE,");
              selectSQLBuffer.append("RES_PHONE_OFFICE,");
              selectSQLBuffer.append("RES_PHONE_OFFICE2,");
              selectSQLBuffer.append("RES_PHONE_OFFICE_FAX,");
              selectSQLBuffer.append("RES_PHONE_HOME,");
              selectSQLBuffer.append("RES_PHONE_HOME2,");
              selectSQLBuffer.append("RES_PHONE_HOME_FAX,");
              selectSQLBuffer.append("RES_MOBILE,");
              selectSQLBuffer.append("RES_PAGER,");
              selectSQLBuffer.append("RES_STATUS,");
              selectSQLBuffer.append("RES_GENDER,");
              selectSQLBuffer.append("RES_BIRTH_DATE,");
              selectSQLBuffer.append("RES_MARTIAL_STATUS,");
              selectSQLBuffer.append("RES_LANGUAGE,");
              selectSQLBuffer.append("RES_CURRENCY,");
              selectSQLBuffer.append("RES_PHOTO,");
              selectSQLBuffer.append("RES_CREATED_BY,");
              selectSQLBuffer.append("RES_NAME_INITIALS,");          
              selectSQLBuffer.append("RES_CREATED_DATE,");
              selectSQLBuffer.append("RES_UPDATED_BY");
              selectSQLBuffer.append("RES_UPDATED_DATE,");
              selectSQLBuffer.append("RES_NAME_FIRST,");
              selectSQLBuffer.append("RES_NAME_LAST,");
              selectSQLBuffer.append("RES_NAME_MIDDLE");     
              selectSQLBuffer.append(" FROM T_RESOURCES WHERE RES_ID="+resourceId);
              String fetchSQL=selectSQLBuffer.toString();
    System.out.println("fetchSQL---"+fetchSQL);
                   DBManager dbManager=new DBManager();
                   Connection con =dbManager.getConnection();
                   Statement stmt=con.createStatement();
                   ResultSet rs=stmt.executeQuery(fetchSQL);
                   ResourceBO resource=new ResourceBO();
                   while(rs.next()){                    
                   resource.setId(rs.getLong(1));
                   resource.setName(rs.getString(2));
                   resource.setCountryCode(rs.getString(3));
                   resource.setLogonPassword(rs.getString(4));
                   resource.setResourceTypeCode(rs.getLong(5));     
                   resource.setResourceParent(rs.getLong(6));
                   resource.setHKey(rs.getLong(7));          
                   resource.setDisplayName(rs.getString(8));
                   resource.setNameTitle(rs.getString(9));
                   resource.setJobTitle(rs.getString(10));
                   resource.setEmail(rs.getString(11));
                   resource.setEmail2(rs.getString(12));          
                   resource.setPasswordAction(rs.getString(13));
                   resource.setPasswordUpdateDate(rs.getDate(14));
                   resource.setPasswordExpireDate(rs.getDate(15));
                   resource.setAccessCode(rs.getString(16));
                   resource.setLogonUnSuccessTries(rs.getLong(17));
                   resource.setWebPage(rs.getString(18));
                   resource.setPhoneOffice(rs.getString(19));
                   resource.setPhoneOffice2(rs.getString(20));
                   resource.setPhoneOfficeFax(rs.getString(21));
                   resource.setPhoneHome(rs.getString(22));
                   resource.setPhoneHome2(rs.getString(23));
                   resource.setPhoneHomeFax(rs.getString(24));
                   resource.setMobile(rs.getString(25));
                   resource.setPager(rs.getString(26));
                   resource.setStatus(rs.getString(27));     
                   resource.setGender(rs.getString(28));     
                   resource.setBirthDate(rs.getDate(29));
                   resource.setMartialStatus(rs.getString(30));
                   resource.setLanguage(rs.getString(31));
                   resource.setCurrency(rs.getString(32));
                   resource.setPhoto(rs.getString(33));
                   resource.setCreatedBy(rs.getLong(34));
                   resource.setInitials(rs.getString(35));                         
                   resource.setCreatedDate(rs.getDate(36));
                   resource.setUpdatedBy(rs.getLong(37));
                   resource.setUpdatedDate(rs.getDate(38));
                   resource.setFirstName(rs.getString(39));
                   resource.setLastName(rs.getString(40));
                   resource.setMiddleName(rs.getString(41));          
                   con.close();
                   con=null;
                   return resource;
    }//end of class
    plz help me to solve this problem....
    rajkumar

    The JSP wil be converted into a java file and then compiled into a class. If you are using tomcat, the java file will be somewhere in the work folder of your tomcat installation. Find the java file and check the line that is reported in the exception to see where the null-pointer is coming from.

  • Wondering how we can invoke static method g() from non-static method d()

    class A {
    final int x;
    A() {
    x = 1;
    int f() {
    return d(this,this);
    int d(A a1, A a2) {
    int i = a1.x;
    g(a1);
    int j = a2.x;
    return j - i;
    static void g(A a) {
    // uses reflection to change a.x to 2
    }

    public class A {
         final int x;
         A() {
              x = 1;
         int f() throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
              return d(this,this);
         int d(A a1, A a2) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
              int i = a1.x;
              g(a1);
              int j = a2.x;
              return j - i;
         static void g(A a) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
              // uses reflection to change a.x to 2
              //a.getClass().getField("x").setInt(a, 5);
              a.getClass().getDeclaredField("x").setInt(a, 5);
         public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException{
              A a = new A();
              System.out.println(a.f());
    throws this exception:
    Exception in thread "main" java.lang.IllegalAccessException: Can not set final int field A.x to (int)5
         at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:55)
         at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:79)
         at sun.reflect.UnsafeQualifiedIntegerFieldAccessorImpl.setInt(UnsafeQualifiedIntegerFieldAccessorImpl.java:114)
         at java.lang.reflect.Field.setInt(Field.java:802)
         at A.g(A.java:22)
         at A.d(A.java:13)
         at A.f(A.java:9)
         at A.main(A.java:27)

  • JUNIT : how to call static methods through mock objects.

    Hi,
    I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
    Can any one suggest me that how can I call static methods through mock objects.

    The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
    Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
    that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
    instead of :
    public class Helper() {
        public static void getSomeHelp();
    public class MockHelper() {
        public static void getSomeHelp();
    }do :
    public class ClassUnderTest {
        private Helper helper;
        public void methodUnderTest() {  // unchanged
            helper.getSomeHelp();
    public interface Helper {
        public void getSomeHelp();
    public class HelperImpl implements Helper {
        public void getSomeHelp() {
            // actual implementation
    public class MockHelper implements Helper {
        public void getSomeHelp() {
            // mock implementation
    }

  • Static methods in javafx class.

    How do I create static methods in javafx similar to static methods in java?

    Hi swamyv,
    I haven't tried declaring any static functions but I know that you can declare static variables by placing them in the script file, but not inside a class definition.
    Something like this:
    package com.mycompany.somepackage;
    public static def ID:String = "someString";
    public class SomeClass {
    }In this case you refer to the static variable by the name of the file, not the name of the class (even though they might be the same).
    e.g. If the above code was in a file called SomeFile.fx, you would refer to the variable as SomeFile.ID.
    Maybe you could try defining a function in the same way.
    Cheers,
    Kevin

  • Overriding static method

    hi all
    can be override static method.if yes then how?plz explain.

    Static methods do hide rather than override - the superclass-and-above methods are, however, visible via explicit referencing. Example:
    public class Foo
         public static final void main(String[] args)
              Foo.foo();
              Poo.foo();
              Foo.bar();
              Poo.bar();
         public static void foo()
              System.out.println("Foo foo");
         public static void bar()
              System.out.println("Foo bar");
         public static class Poo extends Foo
              public static void foo()
                   System.out.println("Poo foo");
              public static void bar()
                   System.out.print("Poo bar, calling foo(): ");
                   foo();
    }Gives
    Foo foo
    Poo foo
    Foo bar
    Poo bar, calling foo(): Poo fooAlways more interesting to try stuff and just see what happens, don't you think? :o)
    Message was edited by:
    itchyscratchy - line wrap pasting error

  • Help on calling static method in a multithreaded environment

    Hi,
    I have a basic question.. pls help and it is urgent.. plss
    I have a class with a static method which does nothing other than just writing the message passed to a file. Now i have to call this static method from many threads..
    What actually happens ???
    Does all the thread start to execute the static method or one method executes while the other threads wait for the current thread to complete execution?. I am not talking about synchronizing the threads...my question is what happens when multiple threads call a static method??
    Pls reply.. I need to design my project accordingly..
    Thanks
    Rajeev

    HI Omar,
    My doubt is just this..
    I wanted to know what might happen if two threads try to access a static method.. Logically only one thread can use the method since it is only only copy... but i was wondering what might happens if f threads try to access the same static method.. My Situation is this.. I have a cache which is just a hash table which will be only one copy for the whole application.. No when i get a request I have to check if the id is avaible in the cache. if it is available i call method 1 if not i call method2. Now Ideally the cache should be a static object and the method to check the id in the cache will be a normal instance method..
    I was just wondering what might happen if i make the method static.. If i can make it static i can can save a lot of space by not creating the object each time.. u know what i mean.. That y i wanted to know what happens..
    Rajeev

  • Static Block vs Static Method

    Hi,
    what is the diff. b/w declaring the variable inside the static block vs static method?
    Why static block is executed first before static method?
    Once the class has been loaded inside the memory the static block will automatically executed by the compiler & it will executed before any static methods. What is the reason behind this why? static block is executed before static method? Please do provide an answer for this..
    Thanks,
    JavaLover

    Um.
    A static method is like a regular method; it only gets called if its...called.
    public class Test
      static
         //this stuff executes after being loaded into memory
      public static void main(string args[])
        //this main method is executed by the VM when you execute "java Test"
        staticMethod(); // this makes the program call staticMethod();
      public static void staticMethod()
        //this code wouldn't be executed if main(string[]) hadn't called it.
    }Hope everything I've said here is correct.

  • How to get the class name  static method which exists in the parent class

    Hi,
    How to know the name of the class or reference to instance of the class with in the main/static method
    in the below example
    class AbstA
    public static void main(String[] args)
    System.out.println(getXXClass().getName());
    public class A extends AbstA
    public class B extends AbstA
    on compile all the class and run of
    java A
    should print A as the name
    java B
    should print B as the name
    Are there any suggestions to know the class name in the static method, which is in the parent class.
    Regards,
    Raja Nagendra Kumar

    Well, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
    you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
    The need we have is this
    I have the test cases inheriting from common base class.
    When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
    In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
    I applicate your inputs on a better way to design without replicating the code..
    In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
    I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
    Regards,
    Raja Nagendra Kumar
    Edited by: rajanag on Jul 26, 2009 6:03 PM

  • How to execute the method of a class loaded

    Hi,
    I have to execute the method of com.common.helper.EANCRatingHelper" + version
    version may be 1,2, etc
    if version = 1 the class is com.common.helper.EANCRatingHelper1;
    Iam able to load the class using following code.But iam unable to execute the method of the above class
    Can anybody help me how to execute the method of the class loaded.
    Following is the code
    String version = getHelperClassVersion(requestDate);
    String helperClass = "com.redroller.common.carriers.eanc.helper.EANCRatingHelper" + version;
    Class eancRatingHelper = Class.forName(helperClass);
    eancRatingHelper.newInstance();
    eancRatingHelper.saveRating(); This is not executing throwing an error no method.
    Thanks

    eancRatingHelper.newInstance();Ok, that creates an instance, but you just threw it away. You need to save the return of that.
    Object helper = eancRatingHelper.newInstance();
    eancRatingHelper.saveRating(); This is not executing throwing an error no method.Of course. eancRatingHelper is a Class object, not an instance of your EANCRatingHelper object. The "helper" object I created above is (though it is only of type "Object" right now) -- you have to cast it to the desired class, and then call the method on that.
    Hopefully EANCRatingHelper1 and 2 share a common interface, or you're up the creek.

Maybe you are looking for

  • Attachments (word docs and PDFs) to emails can not be opened by the receivers. Are received as .dat files or application/octet-stream

    Attachments I add to emails (word doc or PDFs) can not be opened by the email receivers. Word documents attachments are received with ATT00427.dat (application/octet-stream) or .doc with (application/octet-stream). PDF attached files arrive with .pdf

  • Expand or stretch HDTV

      Sometimes pressing the HD Zoom button on my remote will Zoom, Expand, or Stretch the screen on my Samsung HDTV. Sometimes it will not!  Changing the settings for my TV has no effect. 1080,720.480 does not matter. Thursday night I could Zoom the TV

  • Need code help

    Could somebody add an OK button to this code so that when it is clicked a dialog box would pop-up stating the name and which options were selected? Thanks. import java.awt.*; import java.awt.event.*; import java.applet.*;   <applet code="Lister" widt

  • CURRENT_ROW_BACKGROUND_COLOR

    How to use CURRENT_ROW_BACKGROUND_COLOR property dynamically in the forms? Any help will be appreciated. thanks Siva null

  • Installing Aperture without serial

    I am trying to install Aperture 1 on my new computer, but I have lost the packaging. How do I install without a SN?