Using strings within different classes...help!!!!!!!

Plz tell me how i can access a string that is defined in a another class.For example I have a string defined in a class i need to access it in a another class .The dot operator doesnt work unless the class in which string is defined is instantiated in the class where i need to access it.How do i do it then? .Iam not able to write a method to access the string (Smebody in the forum had suggested writing a method).Plz help me out?.The string is entered as user input during runtime .

I should correct myself. Please post code that will also run as a program on our boxes. Also, in your current code Clicka doesn't have a Click object anywhere.
One problem I see is in your first program Click is acting as an ActionListener, and your input string will only become available after the ActionListener has fired. So any program that wants the input String had better only request it after the listener has fired, has had its actionPerformed method called. So in this situation, how do you notify any interested programs that this has happened? One way is to use the observer pattern. This can be simply applied using a ChangeListener like so:
Click.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Click implements ActionListener
  private String input = "";
  List<ChangeListener> changeListeners = new ArrayList<ChangeListener>();
  public void actionPerformed(ActionEvent event)
    input = JOptionPane
        .showInputDialog("Enter the location of hex file (example C://new.txt");
    JOptionPane.showMessageDialog(null, "You have selected " + input);
    ChangeEvent e = new ChangeEvent(this);
    for (ChangeListener cl : changeListeners)
      cl.stateChanged(e);
  public void addChangeListener(ChangeListener cl)
    changeListeners.add(cl);
  public String getInput()
    return input;
}UseClick.java
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class UseClick
  private JPanel mainPanel = new JPanel();
  private Click click;
  private JTextField textField = new JTextField(15);
  public UseClick()
    click = new Click();
    click.addChangeListener(new ChangeListener()
      public void stateChanged(ChangeEvent e)
        String input = click.getInput();
        textField.setText(input);
    JButton clickBtn = new JButton("Click");
    clickBtn.addActionListener(click);
    textField.setEditable(false);
    mainPanel.add(clickBtn);
    mainPanel.add(textField);
  public JPanel getMainPanel()
    return mainPanel;
  private static void createAndShowUI()
    JFrame frame = new JFrame("UseClick");
    frame.getContentPane().add(new UseClick().getMainPanel());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  public static void main(String[] args)
    java.awt.EventQueue.invokeLater(new Runnable()
      public void run()
        createAndShowUI();
}

Similar Messages

  • Same parameter-map used on 2 different classes

    Greetings,
    If the same parameter-map (type connection or http) is used on two different policy-map classes, will that create a conflict in how traffic for each of serverfarms uses persistence or inactivity timeout (script 1)?
    Should we create a different instance of parameter-maps for each policy-map class (script 2)?
    Script 1
    parameter-map type connection inactivity_2000
    set timeout inactivity 2000
    parameter-map type http persistence-rebalance
    persistence-rebalance
    policy-map multi-match L4_POLICY
    class L3-4_VIP_A
    connection advanced-options inactivity_2000
    appl-parameter http advanced-options persistence-rebalance
    loadbalance policy L7_Serverfarm_A_Policy
    loadbalance vip inservice
    loadbalance vip icmp-reply active
    class L3-4_VIP_B
    connection advanced-options inactivity_2000
    appl-parameter http advanced-options persistence-rebalance
    loadbalance policy L7_Serverfarm_B_Policy
    loadbalance vip inservice
    loadbalance vip icmp-reply active
    Script 2
    parameter-map type connection L3-4_VIP_A_connection
    set timeout inactivity 2000
    parameter-map type connection L3-4_VIP_B_connection
    set timeout inactivity 2000
    parameter-map type http L3-4_VIP_A_http
    persistence-rebalance
    parameter-map type http L3-4_VIP_B_http
    persistence-rebalance
    policy-map multi-match L4_POLICY
    class L3-4_VIP_A
    connection advanced-options L3-4_VIP_A_connection
    appl-parameter http advanced-options L3-4_VIP_A_http
    loadbalance policy L7_Serverfarm_A_Policy
    loadbalance vip inservice
    loadbalance vip icmp-reply active
    class L3-4_VIP_B
    connection advanced-options L3-4_VIP_B_connection
    appl-parameter http advanced-options L3-4_VIP_B_http
    loadbalance policy L7_Serverfarm_B_Policy
    loadbalance vip inservice
    loadbalance vip icmp-reply active
    Thanks

    you can reuse the same parameter map.
    Gilles.

  • Use String as name class

    Hello, I have a class name on a string variable, and a method name on other string variable. I would like use this strings to invoke class and it's method, how can i do it? Thanks�����
    For example:
    String class_name = car //name of a class
    String method_name = getOwner // class car method
    // How can I invoke the class and method with this strings?

    // How can I invoke the class and method with this
    strings?Java isn't designed to handle this kind of programming. Java uses strong type checking to make programs more safe. If you often end up wanting to do this why not use a more free-wheeling scripting language instead, such as Groovy,
    http://www-128.ibm.com/developerworks/java/library/j-pg07195.html

  • Trying to understand methods - calling methods within own class - help

    I'm trying to write a simple program to search for letters in a string. I'm having a ton op problems; java seems so complicated with a lot of rules.
    The main problem I'm having (for now) is calling a method within the same class as main.
    import java.io.*;
    class LookForLetters{
        public static void main(String[] args)
         int i = 0;     
         int j = 0;
         int l = 0;
         int m = 0;
         String question1 = "Enter the line to be searched"; 
         String question2 = "Enter the line to be searched";       
         returnResponse stringtosearch = new returnResponse(question1); // here's where my problem is
            char[] chartosearch = stringtosearch.toCharArray();
         returnResponse letterstofind = new returnResponse(question2);
            char[] chartofind = letterstofind.toCharArray();     
         int findlength = chartosearch.length();
         int searchlength = chartofind.length();
         int[] k = new int[searchlength];
         for(i = 0; i < findlength; i++)
             for(j = 0; j < searchlength; j++)   
              if(chartosearch[i] == chartofind[j])
                  k[l] = i;
                  l++;
                  System.out.print("T");
             System.out.print(i + " " + l);
                if(l == 0)
                    System.out.print(chartofind[i] + " is the not in the sentence.");
                    System.out.println();       
                else
                    System.out.print(chartofind[i] + " is the ");
                 for(m = 0; m < l; m++)
                     System.out.print(k[l] + " ");
                    System.out.print("letter of your sentence");
                    System.out.println();
                    l = 0;
        public String returnResponse(String question){
         String response = " ";
         System.out.print(question);
         try
             InputStreamReader isr = new InputStreamReader(System.in);
                BufferedReaderbr = new BufferedReader(isr);
             response = br.readLine();            
         catch(IOException e)
             System.out.print("error");
         return response;
    }The compiler says that it can't find the returnResponse method. when I try to instantiate the whole class, it says the package is not included. Please help.

    JoachimSauer wrote:
    DaneWKim wrote:
    thank you very much for your response. I'm sure it's obvious that I'm really confused. I'm used to C and assembly programming, so the OO concepts are really foggy.That particular line doesn't even deal with any OO concept. But the fact that you already know C helps me give a (hopefully) more useful answer:
    What is the return type of the method you're trying to call?
    What is the type of the variable you want to assign the return value to?
    Are those compatible? Or even more general: do they both exist?I changed it to:
            String stringtosearch = returnResponse(question1);
            char[] chartosearch = stringtosearch.toCharArray();
         String letterstofind = returnResponse(question2);
            char[] chartofind = letterstofind.toCharArray();I guess I'm getting confused with medthods, class and types. There's a whole host of new vocabulary and rules with OO and java that have me a bit confused. I appreciate your help.

  • How to use get im different class?

    Hello, I am new to this java. I need your help, please
    I have Rental class that I use for my RentalApplication to run my Number of items rented & Total of Sale.
    However it gives me 0 instead of the number. Where did I write wrong code?
    public class Rental {
         //Declare variables
         public static final double COST_OF_NEW_RELEASES = 2.25;
         public static final double COST_OF_REGULAR_VIDEO = 1.00;
         public static final double COST_OF_DVDS = 2.98;
         public static final double COST_OF_GAMES = 4.50;
         private int NewReleases;
         private int RegularVideo;
         private int Dvds;
         private int Games;
         private Date timeOfSale;
         private int customerNumber;
         private String customerRental;
         //Constructor method
         public Rental(int theCustomerNumber) {
              timeOfSale = new Date();
              customerNumber = theCustomerNumber;
              NewReleases = 0;
              RegularVideo = 0;
              Dvds = 0;
              Games = 0;
              System.out.println(customerRental = "\nCustomer Number " + customerNumber);
         public Rental(
              int theNumberOfNewReleases,
              int theNumberOfRegularVideo,
              int theNumberOfDvds,
              int theNumberOfGames) {
              this.NewReleases = theNumberOfNewReleases;
              this.RegularVideo = theNumberOfRegularVideo;
              this.Dvds = theNumberOfDvds;
              this.Games = theNumberOfGames;
              this.timeOfSale = new Date();
         //Getters
         public int getNumberOfNewReleases() {
              return NewReleases;
         public int getNumberOfRegularVideo() {
              return RegularVideo;
         public int getNumberOfDvds() {
              return Dvds;
         public int getNumberOfGames() {
              return Games;
         //Other Methods
         public double rentalCost() {
              * Rental Cost()
              * creation date ("2/5/03" 1:30PM)
              return NewReleases * COST_OF_NEW_RELEASES
                   + RegularVideo * COST_OF_REGULAR_VIDEO
                   + Dvds * COST_OF_DVDS
                   + Games * COST_OF_GAMES;
         public String getCustomerRental() {
              return customerRental;
         public int totalAmountRented() {
              return NewReleases + RegularVideo + Dvds + Games;
         public Date getTimeOfSale() {
              return timeOfSale;
         public String getFormatteddatetimeOfSale() {
              DateFormat dateFormat = DateFormat.getDateInstance();
              return dateFormat.format(timeOfSale);
         public String getFormattedRentalCost() {
              * rentalCost()
              * creation date ("1/30/03" 1:30PM)
              NumberFormat dollarFormat = NumberFormat.getCurrencyInstance();
              return dollarFormat.format(rentalCost());
         public String toString() {
              String classDescription = "Thank You for renting";
              classDescription += " ";
              classDescription += "\nRental" + "[";
              classDescription += "New Releases = ";
              classDescription += NewReleases;
              classDescription += ", Number of Regular Video = ";
              classDescription += RegularVideo;
              classDescription += ", Number of DVDs = ";
              classDescription += Dvds;
              classDescription += ", Number of Games = ";
              classDescription += Games;
              classDescription += "]" + ", \n[" + "Time of Sale = ";
              classDescription += getFormatteddatetimeOfSale();
              classDescription += ", Rental Cost = ";
              classDescription += getFormattedRentalCost();
              classDescription += "]";
              return classDescription;
         public static void main(String[] args) {
              Rental theRental;
              theRental = new Rental(3, 1, 3, 1);
              System.out.println(theRental.toString());
         * Method findRentalItems.
         * @param thevideoId
         * @return RentalItems
         public static RentalItems findRentalItems(String thevideoId) {
              return null;
    This is my RentalApplication
    public class RentalApplication
         public static void main(String[] args)
              Rental theRental;
              RentalItems theRentalItems;
              VideoStore theVideoStore = new VideoStore();
              int customerNumber = 1;
              boolean newCustomer = true;
              boolean moreLookUps = true;
              String thevideoId;
              NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
              DateFormat dateFormat = DateFormat.getDateTimeInstance();
              while (newCustomer)
                   theRental = new Rental(customerNumber);
                   while (moreLookUps)
                        thevideoId = JOptionPane.showInputDialog("Enter Video Id's");
                        theRentalItems = RentalItems.findRentalItems(thevideoId);
                        System.out.println(theRentalItems.displayRentalItems());
                        moreLookUps = getOption("Another Videos?");
                   theVideoStore.addRental(theRental);
                   System.out.println("Time of sale: "+ dateFormat.format(theRental.getTimeOfSale())
                                       + "\tNumber of items rented "
                                       + (theRental.totalAmountRented())
                                       + "\tTotal of Sale: "
                                       + numberFormat.format(
                                            theRental.rentalCost()));
                   newCustomer = getOption("Another Customer");
                   moreLookUps = true;
                   customerNumber++;
              System.out.println(theVideoStore.displayVideoStore());
              System.exit(0);
         public static int readInt(String prompt) {
              return Integer.parseInt(JOptionPane.showInputDialog(prompt));
         public static boolean getOption(String prompt) {
              int theNum;
              theNum = JOptionPane.showConfirmDialog(null, prompt);
              return (theNum == 0);

    In your RentalApplication main() method, you do the following:
    theRental = new Rental(customerNumber);which calls the
    public Rental(int theCustomerNumber)constructor.
    In that constructor, you initialize
    NewReleases = 0;
    RegularVideo = 0;
    Dvds = 0;
    Games = 0;But nowhere do you ever adjust those values. So the reason you're getting 0 back, I believe, is because that's what you set them to.

  • Using variables in different classes

    Hi,
    A very basic question!
    i've got a 2d array in one class, which I want another class to be able to see. Is there any way I can do this in Java - if so, how? If not, is there a way around this?
    Thanks

    Or don't put it in a class, put it into an interface instead; have both classes impelement it.
    ~Bill

  • Accessing a different class using ActionPerformed

    hi
    im trying to access a method in a different class using
    public void actionPerformed (ActionEvent e) {
              if(e.getSource() == AuthorCombo) {
                   ComboAction();
              else if(e.getSource() == SearchButton){
                        SearchSystem();
    }and then using
    public class Book extends ViewPanel{
    public void SearchSystem(){// this is used to get the information from
                      //the combo boxs whixh can latter show
                      //the data in the text area
    tempBookNoList.clear();
              for(int a=0; a<AuthorList.size(); a++) {
                                  if(((String)AuthorCombo.getSelectedItem()
                                  ==AuthorList.get(a))
                                  &&((String)BookCombo.getSelectedItem()
                                  ==BookList.get(a))) {
                                       tempBookNoList.add((String)BookNoList.get(a));
                        String result = (String)tempBookNoList.get(a);
                        InfoArea.setText ((String)tempBookNoList.get(a));
    }          }//End neither random situation.to manipulate some data within the other class
    i keep getting the error
    .\ViewPanel.java:314: cannot resolve symbol
    symbol : method SearchSystem ()
    location: class ViewPanel
                        SearchSystem();
    ^
    1 error
    can anyone help me spot the problem

    in that case i do not know what could be the cause in this program
    the only area i think it could be is when the SearchSystem method in the Book class gets using the Action Performed method in the Viewpanel method, shown below
    public class Book extends ViewPanel{
    public void SearchSystem(){// this is used to get the information from
                      //the combo boxs whixh can latter show
                      //the data in the text area
              for(int a=0; a<AuthorList.size(); a++) {
                                  if(((String)AuthorCombo.getSelectedItem()
                                  ==AuthorList.get(a))
                                  &&((String)BookCombo.getSelectedItem()
                                  ==BookList.get(a))) {
                                  InfoArea.setText((String)BookNoList.get(a));
                   }which is called using
    public void actionPerformed (ActionEvent e) {
              if(e.getSource() == AuthorCombo) {
                   ComboAction();
              else if(e.getSource() == SearchButton){
                        theBook.SearchSystem();
    }but i cant see this being a problem as it all compiles

  • Arrays within custom Classes - same array for different instances?

    Hello all,
    I have made a very simple custom class for keeping track of groups of offices for a company.  The class has a Number variable to tell it how many different offices there are, and an Array to store the individual offices by name.  It looks like this.
    class officeCluster
        static var _className:String = "officeCluster";
        // variables
        var numOffices:Number;
        var locationArray:Array = new Array();
        // functions
        function officeCluster()
            trace("officeCluster constructor");
    Very simple!
    Now, it is my understand that when I create different instances of the class, they will each have their own version of "numOffices" and their own version of "locationArray".
    When I run traces of "numOffices", this seems to be true.  For example,
    trace(manufacturingOfficeCluster.numOffices);
    trace(servicesOfficeCluster.numOffices);
    yields
    5
    4
    In the output panel, which is correct.  However, there is trouble with the locationArray.  It seems that as I assign different values to it, regardless of what instance I specify, there is only ONE array- NOT one for each instance.
    In other words,
    trace(manufacturingOfficeCluster.locationArray[1].theLocation);   // theLocation is a String.  The locationArray itself holds Objects.
    trace(servicesOfficeCluster.locationArray[1].theLocation);
    yields
    New Haven, CT
    New Haven, CT
    even though I have defined elsewhere that they are different!
    Is anyone aware of any issues partaining to using Arrays within Class instances?  Any help would be appreciated!
    note:  I've been able to work around this by creating multiple arrays within the class and using a different one for each instance, but this seems very sloppy.

    Unfortunately, the code segment you attached results in:
    12
    12
    in the output panel.   So the problem must lie elsewhere!  Let me give some more detail...
    There are several files involved. The "officeCluster" class file looks like this:
    class officeCluster
         static var _className:String = "officeCluster";
         // variables
         var numOffices:Number;
         var locationArray:Array = new Array();
         // functions
         function officeCluster()
            trace("officeCluster constructor");
    I have two actionscript files which contain object data for the individual offices.  They look like this...
    var servicesOfficeCluster = new officeCluster();
    servicesOfficeCluster.numOffices = 4;
    var newHope:Object = new Object();
    newHope.locationName = "New Hope Office";
    newHope.theLocation = "New Hope, NJ";
    //more data
    servicesOfficeCluster.locationArray[0] = newHope; //array index is incremented with each entry
    //more Objects...
    and like this...
    var manufacturingOfficeCluster = new officeCluster();
    manufacturingOfficeCluster.numOffices = 5;
    var hartford:Object = new Object();
    hartford.locationName = "Hartford Office";
    hartford.theLocation = "Hartford, CT";
    //more data
    manufacturingOfficeCluster.locationArray[0] = hartford; //array index is incremented with each entry
    //more Objects...
    As you can see, the only difference is the name of the officeCluster instance, and of course the Object data itself.  Finally, these are all used by the main file, which looks like this- I have commented out all the code except for our little test -
    import officeCluster;
    #include "manufacturingList.as"
    #include "servicesList.as"
    /*lots of commented code*/
    manufacturingOfficeCluster.locationArray[1].theLocation = "l1";
    servicesOfficeCluster.locationArray[1].theLocation = "l2";
    trace(manufacturingOfficeCluster.locationArray[1].theLocation);
    trace(servicesOfficeCluster.locationArray[1].theLocation);
    Which, unfortunately, still yields
    12
    12
    as output :\  Any ideas?  Is there something wrong with the way I have set up the class file?  Something wrong in the two AS files?  I'm really starting to bang my head against the wall with this one.
    Thanks

  • Using System.err.println() from within the classes of WAS ?

    hi,
    I am using admin.jar,a jar file which is being used by Web Application Server in my own class.
    I am referencing some of the classes from admin.jar from my class.
    I tried to print some trace statements,using System.err.println() from within the classes in admin.jar but they did not reflect in defaulttrace0.trc.
    I made these changes in the admin.jar being used by WAS.
    I restarted the server and even restarted the machine but without success.
    I want to know how to print System.out.println() statements from within the classes in admin.jar.
    Also, am i looking for these statements in the right file for eg. defaulttrace0.trc. or is it some other file that i need to look into.
    I need urgent help on this.
    Reward points assured.
    thanks a lot.
    Saurav

    thanks craig,
    ur answer has helped me a lot.but it didnt quite help me.
    nevertheless i am trying to set different levels of severity.
    Is there anything else that i can do.
    Also,i commented out a line of code today in one of the class DataSourceManagerImpl.java in sapj2eenginedeploy.jar
    for eg. temp.delete in it deploy method.Buth that line still executed.
    I m totally lost as to wht to do.
    I m trying to create a datasource from my application in WAS.For that i m using the WAS APIs.But its not working completely.
    I am using the above jar and its method createdatasource.
    I am callin it from my application's class.
    It creates a datasource and i can see it in JDBC Connector list in Visual Administrator.But it appears with red sign meaning its not started.When i start it from the tool then it starts.
    But in defaulttrace.trc file it shows an error "FileNotFindException". This happens,and i am very much sure, in the deploy() of DataSourceManagerImpl.java class of sapj2eenginedeploy.jar.
    i want to apply println inside this method so i may know where exactly i ma getting the error and get so more info so i may solve my problem.
    pls help me.
    its really urgent.
    thanks again
    saurav

  • Using Buffered Writer In Different Classes

    Hi,
    I have 4 different classes in my program. Although the three object defining classes have accessor methods, I use print functions designed within them. I'm wondering if it is at all possible to use a single buffered reader to use all of the classes. Thanks for the help.

    Possible, yes.Wow that doesn't sound reassuring haha..
    Well I decided to stop being lazy and recreated the print function as a writing function using the accessors, but now I'm having an issue between methods. Is it possible to use the same bufferedreader easily[i] between different methods?

  • Help! -- different class loader issue

    From within an EJB I am trying to cast a serializable object, that was passed into this EJB, to its original type. The process ended with a ClassCastException, even though I have double checked that the object being casted is of the correct type and fully qualified package path. It turns out that the problem is caused by the involvment of 2 different class loaders -- The class loader that loads the object is not the same one that loads the EJB doing the casting. The thing that confuses me the most is that this program used to work fine without the exception when it was running in an older environment. Is this a VM issue? Do we have control over what class loader to use when load certain classes/objects? What's the fix to the problem?
    Please help!
    Thanks in advance.
    Lifeng

    It is a Java platform version issue. Since Java 2 The classloaders are lay out in a hierarchy. You can read about it in the public chapters of the book "Inside the Java 2 Virtual Machine" by Bill Venners at
    www.artima.com
    This may be helpful for you . It specifies the class loaders used by a thread to load subsequent classes: aThread.setContextClassLoader(aClassLoader)
    Other soulution is to have the object and EJB being loaded by the same class loader, which could be a common parent class loader for the ones that in your code are actually asked to load these objects
    Otherwise, java.lang.reflect can deal with objects whose type is not known by the compiler.

  • How to use the different class for each screen as well as function.

    Hi Experts,
    How to use the different class for each screen as well as function.
    With BestRegards,
    M.Thippa Reddy.

    Hi ThippaReddy,
    see this sample code
    Public Class ClsMenInBlack
    #Region "Declarations"
        'Class objects
        'UI and Di objects
        Dim objForm As SAPbouiCOM.Form
        'Variables
        Dim strQuery As String
    #End Region
    #Region "Methods"
        Private Function GeRate() As Double
                Return Double
        End Function
    #End Region
    Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
            If pVal.BeforeAction = True Then
                If pVal.MenuUID = "ENV_Menu_MIB" Then
                End If
            Else ' Before Action False
                End If
        End Sub
    #End Region
    End Class
    End Class
    Rgds
    Micheal
    Vasu Anna Regional Feeling a???? Just Kidding
    Edited by: micheal willis on Jul 27, 2009 5:49 PM
    Edited by: micheal willis on Jul 27, 2009 5:50 PM

  • How to accept 2 strings in a class with try catch method..help!!

    the program below will accept two strings and compare str1 and str2 if equal. this program uses functions. can any one help me with this?
    import java.io.*;
    public class StrCompare {
         private BufferedReader takyoin = null;
         //private BufferedReader intakyo = null;
         * @param args
         public StrCompare(){
              takyoin = new BufferedReader(new InputStreamReader(System.in));
              //intakyo = new BufferedReader(new InputStreamReader(System.in));
         public String UserInput(){
         public static void main(String[] args) {
              // TODO Auto-generated method stub
    }

    What are you talking about? There is no such thing as "try-catch-methods", and there are no functions but methods.
    Strings by the way have their own means of comparision. Apart from that: do your own homework.

  • Using Excel Active X to Find a String within a column

    I am trying to use ActiveX functions to search for a string within a specific column in excel. And return the row index of that string if a match occurs. Any help on that will be appreciated. I used Read then Compare for each cell in that column, but it is too slow. Maybe a search will be faster.

    Here are some Vi's that will allow you to do a "find" just like doing the edit find function in excel. There is also a vi in there to do a search and replace.
    Joe.
    "NOTHING IS EVER EASY"
    Attachments:
    replace.llb ‏117 KB

  • 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.

Maybe you are looking for