Method calling

Hello,
I have a problem in calling a method in say ClassA from ClassB. In my scenario, ClassA knows the name of the calling class, namely ClassB as it has been stored only as a string variable.
So, In ClassA, I have a declaration statement like
String name=classB;
And I also know the method in classB to be called, say classB.run( ). But, I cant create an object of classB and call its method directly from classA, as I have the classname (classB) only as a value of string variable in classA. This is because, the classname (classB) is known only during runtime, thatis in my case, the classname is a value of an attribute in a xml file that is collected during parsing and rendering stage.
So, can anyone please guide to further proceed with my work.
Thank you,
Shiv.

You can use the reflection API for this:
     * Instantiate Java object from a class by calling the constructor that matches the given parameters.
     * @param className
     * @param classes Constructor parameter types (class names).
     * @param values Constructor parameter values.
     * @return Java object.
     * @throws ClassNotFoundException if class can't be found in classpath.
     * @throws NoSuchMethodException if there's no constructor with the given types.
     * @throws InvocationTargetException if the constructor throws an exception.
     * @throws IllegalAccessException if access to the constructor is denied.
     * @throws InstantiationException if the class is abstract and therefore can't be instantiated.
     * @since 1.8.3
    static public Object getInstance(String className, Class[] classes, Object[] values) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        Object result = null;
        if (className != null) {
            Class c = Class.forName(className);
            if (classes != null && values != null) { //constructor with arguments:
                Constructor cc = c.getConstructor(classes);
                result = cc.newInstance((Object[]) values);
            } else { //empty constructor:
                result = c.newInstance();
        }//else: input unavailable
        return result;
    }//getInstance()
     * Call a (non-static) Java method.
     * @param instance Java object created via the instantiate() method.
     * @param methodName Name of instance method.
     * @param classes Optional method parameter types.
     * @param values Optional method parameter values.
     * @return Result of method call.
     * @throws ClassNotFoundException if parameter type can't be found in classpath.
     * @throws NoSuchMethodException if <i>methodName</i> is invalid.
     * @throws InvocationTargetException if the method throws an exception.
     * @throws IllegalAccessException if access to the method is denied.
     * @since 1.8.3
    static public Object call(Object instance, String methodName,  Class[] classes, Object[] values) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Object result = null;
        if (instance != null && methodName != null) {
            Method method = instance.getClass().getMethod(methodName, classes);
            result = method.invoke(instance, (Object[]) values);
        }//else: input unavailable
        return result;
    }//call()

Similar Messages

  • Taskflow Method call receiving null parameter.

    Hi all,
    I am using 11.1.1.6. I have created in my application an extra project which is pure Java objects and exposed a master class as a POJO DC. In my application, I have a taskflow where I have dragged and dropped one method from my POJO DC - 2 of the parameters of this methods are coming from an application scope bean. I have debugged the application, and made sure that the object being returned by the getter of my app scope bean is not null. So basically, when the breakpoint is in the return statement of my getter the oject is not null and it has been correctly initialized. Just after that, the next breakpoint is in the class receiving the parameter in my POJO DC class. In there, the object is NULL.
    Does anyone knows wat could be the reason??

    Hi Frank Nimphius-Oracle,
    That is precisely the problem.  The object is being passed as to the taskflow as an input parameter (getting it from my application scope bean). If I access the pageFlowScope inside my taskflow I see it and its there, correctely intialized. However, when I call a method call activity that consumes that object as parameter, all what it gets is null.
    The method that consumes this object is in a separate project, and its exposed in a POJO DC. I don't know if it has to be with the complexity of the object I am passing or what but I don't understand why its not being passed correctly to the DC Method.

  • Closing an anonymous stream in method call

    Will an anonymous stream in a method call be closed in the same manner an anonymous stream that is created in an object instantiation will be?
    I know this will close the anonymous FileInputStream:
    DataInputStream in =
    new DataInputStream(new FileInputStream("filename.txt"));
    /* ... code ... */
    in.close();But will this?
    MyPropertiesClass myPropertiesClass = new MyPropertiesClass();
    myPropertiesClass.store(new FileOutputStream("file.txt"));MyPropertiesClass extends Properties, and uses its store().
    I know the JavaDoc for Properties says:
    "After the entries have been written, the output stream is flushed. The output stream remains open after this method returns."
    My question is will the FileOutputStream("file.txt") be closed and garbage collected eventually after this method call because I don't have a reference to it? myPropertiesClass sticks around for a long time afterwards, will the FileOutputStream as well?
    Thanks for any insight,
    KJ

    My question is will the FileOutputStream("file.txt") be closed and garbage collected eventually after this method call because I don't have a reference to it? > myPropertiesClass sticks around for a long time afterwards, will the FileOutputStream as well?Your only hope would be if FileOutputStream overrode finalize and closed the stream there -- but it doesn't (check the API -- finalize isn't overridden). I doubt if Properties retains a reference to the OutputStream you pass to store -- why would it need to? In any case, the bottom line is that output stream isn't being closed until your process exits.
    Why not bite the bullet and rewrite that line of code so that you can explicitly close the stream?
    OutputStream out = new FileOutputStream("file.txt");
    try {
        myPropertiesClass.store(out);
    } finally {
        out.close();
    }It's not one line, but who cares? You could wrap it up in a short utility method:
    static void storeProperties(Properties properties, String path) {...}

  • Using a dynamic variable in the Import command of a Method call

    Hi,
    I am trying to make a Method call fully dynamic.
    I have found out how to make the Method name dynamic, but I am having trouble figuring out how to make the Importing statement dynamic.
    in my code below:
          CALL METHOD o_main->(v_call)
            IMPORTING
              it_ekko = i_ekko.
    I would like to know if it's possible to make both "it_ekko" AND "i_ekko" dynamic so I can use this same call for various tables.
    Hope that makes sense...thanks for your help.
    Andy

    Hi Andrew,
    The method call is fully dynamic; not only the parameters can be specified dynamically but also the method name.
    This is a help extract:
    DATA: line     TYPE c LENGTH 80,
          text_tab LIKE STANDARD TABLE OF line,
          filename TYPE string,
          filetype TYPE c LENGTH 10,
          fleng    TYPE i.
    DATA: meth  TYPE string,
          class TYPE string,
          ptab TYPE abap_parmbind_tab,
          ptab_line TYPE abap_parmbind,
          etab TYPE abap_excpbind_tab,
          etab_line TYPE abap_excpbind.
    DATA: exc_ref TYPE REF TO cx_sy_dyn_call_error,
          exc_text TYPE string.
    class    = 'CL_GUI_FRONTEND_SERVICES'.
    meth     = 'GUI_DOWNLOAD'.
    filename = 'c:\temp\text.txt'.
    filetype = 'ASC'.
    ptab_line-name = 'FILENAME'.
    ptab_line-kind = cl_abap_objectdescr=>exporting.
    GET REFERENCE OF filename INTO ptab_line-value.
    INSERT ptab_line INTO TABLE ptab.
    ptab_line-name = 'FILETYPE'.
    ptab_line-kind = cl_abap_objectdescr=>exporting.
    GET REFERENCE OF filetype INTO ptab_line-value.
    INSERT ptab_line INTO TABLE ptab.
    ptab_line-name = 'DATA_TAB'.
    ptab_line-kind = cl_abap_objectdescr=>changing.
    GET REFERENCE OF text_tab INTO ptab_line-value.
    INSERT ptab_line INTO TABLE ptab.
    ptab_line-name = 'FILELENGTH'.
    ptab_line-kind = cl_abap_objectdescr=>importing.
    GET REFERENCE OF fleng INTO ptab_line-value.
    INSERT ptab_line INTO TABLE ptab.
    etab_line-name = 'OTHERS'.
    etab_line-value = 4.
    INSERT etab_line INTO TABLE etab.
    TRY.
        CALL METHOD (class)=>(meth)
          PARAMETER-TABLE
            ptab
          EXCEPTION-TABLE
            etab.
        CASE sy-subrc.
          WHEN 1.
        ENDCASE.
      CATCH cx_sy_dyn_call_error INTO exc_ref.
        exc_text = exc_ref->get_text( ).
        MESSAGE exc_text TYPE 'I'.
    ENDTRY.
    BR,
    Valentin

  • Error on /SafeMode: error while trying to run project uncaught exception thrown by method called

    i try run VS 2012 with /SafeMode. I create new empty Winform. When I start debug, I got:
    "error while trying to run project uncaught exception thrown by method called through reflection"

    Hi Matanya Zac,
    Did you restart your machine? How about installing the VS2012 update 4?
    >>error while trying to run project uncaught exception thrown by method
    Did you install the VS update in your VS IDE? I met this issue before which was related to the VS update:
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/5ead8ee9-ea09-4060-88b0-ee2e2044ff82/error-while-trying-to-run-a-project-uncaught-exception-thrown-by-method-called-through-reflection?forum=vsdebug
    If still no help, I suggest you repair your VS, and then restart your machine, test the result.
    Best Regards,
    Jack
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • AcquireConnection method call to the connection manager Excel connection Manager failed

    I used VS Studio 2008 (BIDS version 10.50.2500.0) on an WinXp machine (v 5.1.2600 SP3 Build 2600) to create a package that writes multiple query results to different tabbed sheets of a single excel spreadsheet. The package was working just fine and has run
    successfully multiple times, but all of a sudden when opening the project, every single Data Flow task with an Excel Connection Manager displayed error icons. Each raises the following error message when attempting to open the Advanced Editor:
    SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005 Description: "Unspecified error". Error at DataFlow task name: SSIS error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method
    call to the connection manager Excel connection Manager failed with error code 0xC0202009. There may be error messages posted before this with more information on why the Acquire Connection method call failed. Exception from HRESULT: 0Xc020801c (Microsoft.SQlServer.DTSPipelineWrap)
    From the time I created the original package (when it worked fine) until now:
     1) I have been using the same computer, the same login account and the same permissions.
     2) I have been writing to the same (32 bit) 2010 Excel file (which I created) in a folder on my local machine.
     3) The filename and location have not changed; a template file is used each time to move and overwrite the previous file. Both are in the same locations.
     4) I can independently open the target Excel file and the template Excel files with no errors.
     6) The ConnectionString has not changed. The Connnection String I am using is
      Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Conversion\Conversion\Results_dt01.xlsx;Extended Properties="EXCEL 12.0 XML;HDR=YES;".
     7) Run64BitRuntime is set to False.
    8)  Delay Validation is set to true
    9) This is not running under a SQL job  
    10) There are no child packages being run
    I CAN create a NEW Excel Connection Manager, assigning it the exact same target Excel spreadsheet, successfully, but when I attempt to assign it to the Data Flow destination this error occurs:
    "Test connection failed because of an error in initializing provider. Unspecified error."
    Thinking that the driver might be corrupt, I opened a second SSIS package, which also uses the Excel Connection Manager (same driver) and this package continues to work fine on the same workstation with no errors.
    I have searched online for causes of this error for many hours and found nothing that helps me to solve this issue.
    Does anyone have any suggestions for me?

    Yes, I have verified that the Excel file is not in use or opened by anyone, including me. It has been two months since I opened this particular package, although I have been working with other packages in this project. I just discovered that another
    package in the same project has the same problem - all Data Flows that output to an Excel Destination now have the same error icons. This second packages outputs to an entirely different Excel file than in the first package.  A summay:
    Package #1 has error on every Excel Destination and uses templateA to overwrite fileA and then writes to fileA
    Package #2 has error on every Excel Desintation and uses templateB to overwrite fileB and then writes to fileB
    Package #3 has no error on any Excel Destination and is linked to multiple files (none are A or B)
    Package #1 and #2 are in the same project, but Package #3 is in a separate project .
    I will try replacing the Excel files with new ones for Package 1 and 2.

  • [Load data from excel file [1]] Error: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "Excel Connection Manager" failed with error code 0xC0202009. There may be error messa

    Error
    [Load data from excel file [1]] Error: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.  The AcquireConnection method call to the connection manager "Excel Connection Manager" failed with error code 0xC0202009.  There
    may be error message
    I am using BIDS Microsoft Visual Studio 2008 and running the package to load the data from excel .
    My machine has 32 bit excel hence have set property to RUN64BITRUNTIME AS FALSE.
    But the error still occurs .
    I checked on Google and  many have used Delay validation property at Data flow task level to true but even using it at both excel connection manager and DFT level it doesnt work
    Mudassar

    Thats my connection string
    Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\SrcData\Feeds\Utilization.xlsx;Extended Properties="Excel 12.0;HDR=NO";
    Excel 2010 installed and its 32 bit edition
    Are you referring to install this component -AccessDatabaseEngine_x64.exe?
    http://www.microsoft.com/en-us/download/details.aspx?id=13255
    Mudassar
    You can try an OLEDB provider in that case
    see
    http://dataintegrity.wordpress.com/2009/10/16/xlsx/
    you might need to download and install ms access redistributable
    http://www.microsoft.com/en-in/download/details.aspx?id=13255
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • What are the methods called while navigating from one applet to another one

    Hi All,
    Could any one brief me about "When you navigate from one applet to another what are the methods called ?".
    Thanks in advance.
    Best Regards,
    N.Madhusudhanan.

    http://forum.java.sun.com/thread.jsp?forum=421&thread=426771&tstart=0&trange=100

  • Issue with a method call in a TaskFlow (works 2 times instead of 1)

    Hi guys,
    i'm using jdev11.1.1.1.2.0 and the integrated weblo or remote weblo 10.3.2.0.
    I'm encountering a problem with a method call which is invoked inside a Task Flow.
    Let me tell us the details of :
    I'm invoking a method call which is part of a Task Flow from the backingbean of the view which is placed before the method call in the taskFlow diagram.
    AN outcome String from the method of the backing bean allows to navigate to the method of the Task flow.
    The method call is called and works normally BUT MY PROBLEM IS THAT THE METHOD IS CALLED TWO TIMES SO THE RESULT IS FALSE.
    For information, the second time the method is called it takes care of the result when it is invoked the first time. So its parameters are updated and are a little different from the first time to the second time.
    NB : This method consists of inserting a row in the database. My result is 2 rows inserted instead of one.
    Thanks for help for this strange behaviour

    Hi
    create a temp calculated column
    =IF(ISBLANK([Duration]),"",[Item Start Date]+([Duration])
    and check if it's working OK
    Romeo Donca, Orange Romania (MCSE, MCITP, CCNA) Please Mark As Answer if my post solves your problem or Vote As Helpful if the post has been helpful for you.

  • Abstract method called in an abstract class

    Hello,
    I am writing some code that I'd like to be as generic as possible.
    I created an abstract class called Chromozome. This abstract class has a protected abstract method called initialize().
    I also created an abstract class called Algorithm which contains a protected ArrayList<Chromozome>.
    I would like to create a non abstract method (called initializePopulation()) which would create instances of Chromozome, call their method initialize() and full the ArrayList with them.
    In a practical matter, only subclass of Algorithm will be used, using an ArrayList of a subclass of Chromozome implementing their own version of initialize.
    I have been thinking of that and concluded it was impossible to do. But I'd like to ask more talented peaple before forgetting it !
    Thanks,
    Vincent

    Ok, let's it is not impossible, juste that I had no idea of how doing it :-)
    The difficulty is that Algorithm will never have to deal with Chromozome itself, but always with subclass of Chromozome. This is usually not an issue, but in that case, Algorithm is required to create instances of the desired subclass of Chromozome, but without knowing in advance wich subclass will be used (I hope what I say makes any sense).
    Actually I may have found a way in the meantime, but maybe not the best one.
    I created in Algorithm an abstract method :
    protected abstract Chromozome createChromozome()The method initializePopulation will call createChromozome instead of calling directly the constructor and the initialize() method of Chromozome.
    Then subclass of Algorithm will implement the method createChromozome using the desired subclass of Chromozome.

  • Ecatt script fails due "Error in OLE API method Call"  error

    Hi ,
    Ecatt scripts fails due to "Error in OLE API method Call" error, this error message occurs once a while.
    We are calling testpartner scripts from Ecatt using REFEXT command. At times this ECATT script fails due to above issue.
    Please help in solving this issue.
    Thanks,
    Asha

    >
    Asha Nagaraj wrote:
    > Hi ,
    >
    > Ecatt scripts fails due to "Error in OLE API method Call" error, this error message occurs once a while.
    >
    > We are calling testpartner scripts from Ecatt using REFEXT command. At times this ECATT script fails due to above issue.
    >
    > Please help in solving this issue.
    >
    > Thanks,
    > Asha
    Hi Asha,
    Are those components are connected and the necessay settings has been done?
    Regards,
    SSN.

  • *ERROR IN OLE CALL - METHOD CALL ERROR...*

    HI ..
    When trying to Upload a file using BDC with Vista OS, we are getting the following error..
    ERROR IN OLE CALL - METHOD CALL ERROR...
    There is no problem with BDC as its working fine with XP & other OS.
    Pls help!!

    Seems that you are working with microsoft files.
    Maybe you are using deprecated functions like WS_EXCEL

  • Method called reverse that switches complex number coordinates.

    I have written a class called "Complex" and there are no errors in the program.
    What I am confused about is how to answer an assigned question. The question
    is this: "Write a method called reverse which will return a new complex number
    with the coordinates reversed. That is, if the complex number which invokes
    the method has coordinates (a,b), then the method should return a new complex
    value with coordinates (b, a)."
    I will include my code for the class here (I'm using the NetBeans IDE):
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package tutorial8;
    * @author Aleks
    public class Complex
        private int I; // Real Part
        private int J; // Imaginary Part
        public Complex(int I, int J)
        setComplex(I, J);
    public int getI()
        return I;
    public int getJ()
        return J;
    public void setComplex(int I, int J)
    this.I=I;
    this.J=J;
    if (I==J)
    System.out.println("true");
    else
    System.out.println("false");
    }thanks.

    Your right it compiles without errors but it says it's missing a main method.
    This main method thing is driving me insane. Some of my classes work such as the following
    one:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package tutorial7;
    * @author Aleks
    import java.util.Scanner;
    public class Shortcalculation
        public static void main(String[] args)
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter a positive integer");
            int positiveInteger = keyboard.nextInt();
           if (positiveInteger < 2)
            System.out.println("First positive integer output");
            positiveInteger = 4;
            while ((positiveInteger/3 >=1) && (positiveInteger/3 < 2))
                System.out.println("4");
            else if (positiveInteger < 3)
            System.out.println("Second positive integer output");
            positiveInteger = 21;
            while ((positiveInteger/5 >=2) && (positiveInteger/5 < 3))
                System.out.println("21");
            else if (positiveInteger < 4)
            System.out.println("Third positive integer output");
            positiveInteger = 43;
            while (positiveInteger/7 <=3)
                System.out.println("43");
            else
            System.out.println("Not a valid integer");
    }But I don't see why THIS one shouldn't. I try to include a "public static void main(string[] args)"
    in the class complex but it says it's an illegal start of the expression. Maybe it depends on
    where in the class I put it. I'm only practicing writing classes for 3-4 weeks now because I've read
    a lot of the book. Too bad my memory is kind of bad. Ok, I have changed the class for this
    question, I have added a reverse method. I did it without a return statement.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package tutorial8;
    * @author Aleks
    public class Complex {
        private int I; // Real Part
        private int J; // Imaginary Part
        public Complex(int I, int J)
        setComplex(I, J);
        public int getI()
        return I;
    public int getJ()
        return J;
    public void setComplex(int I, int J)
    this.I=I;
    this.J=J;
    if (I==J)
    System.out.println("true");
    else
    System.out.println("false");
    public void reverse()
    this.I=J;
    this.J=I;
    }sorry for the long post.

  • Webservice initialized on every method-call.

    Hello!
    I have written two webservices. One containing a EJB and a SOAP-Webservice and one with just a SOAP-Webservice.
    If I call the EJB-Version the webservice gets inizialized by glassfish on the first call and then stays running (Constructor is not called any more) but if I call the SOAP-only service constructor is called on every method-call.
    Therefore I have a deployment-problem with the EJB-Version: I use SQL-Server-JDBC-Libs in my Netbeans-Project. The get deployed to the server but are not used by the application. Instead I have to copy them to the servers lib-directory. If I deploy them with my Soap-only-service they work...

    For the Webservice-only I create a web-application in Netbeans (File - New Project - Java Web - Web Application) and run this code:
    package com.service;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    @WebService(serviceName = "Service")
    public class Service {
        public Service() {
            System.out.println("Constructor called!");
        @WebMethod(operationName = "hello")
        public String hello(@WebParam(name = "name") String txt) {
            return "Hello " + txt + " !";
    }Everytime i call the hello-method through the Tester (http://ip:port/URI?Tester) the webservice get initialized ("Constructor called").
    On the other hand I create a Java EE - EJB-Module in Netbeans and add the webservice.
    I remove the EJB-Annotations from the module and use it as a POJO for the code.
    EJB:
    package com.slan.ejb;
    import javax.ejb.Stateless;
    @Stateless
    public class EJBSlan {
        public EJBSlan(){
            System.out.println("Constructor of EJB called!");
        public String getHello(String name) {
            return "Hello " + name;
    }Service:
    package com.slan.service;
    import com.slan.ejb.EJBSlan;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.ejb.Stateless;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    @WebService(serviceName = "EJBService")
    @Stateless()
    public class EJBService {
        private EJBSlan ejbRef;
        public EJBService(){
            ejbRef = new EJBSlan();
            System.out.println("Constructor of Service called!");
        @WebMethod(operationName = "getHello")
        public String getHello(@WebParam(name = "name") String name) {
            return ejbRef.getHello(name);
        @WebMethod(operationName = "getMachines")
        public String getMachines() {
            String machines = "";
            try {
                DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                Connection c = DriverManager.getConnection("jdbc:mysql://ip/cm","user","password");
                Statement s = c.createStatement();
                ResultSet r = s.executeQuery("select  from machines");
                while(r.next()){
                    machines += r.getString("comment");
                s.close();
                c.close();
            } catch (SQLException e) {
                System.out.println(e.toString());
            return machines;
    }As you can see I already tried to add the sql-code to query the database. I added the mysql.jar to the project and deployed it. Using the tester the Service- and POJO-Object gets initialized only once but I cant use the mysql-driver cause it is not used on the server. But it gets deployed to the server... I think it's just not included in the class-path...

  • Best practice for method calling on objects within a collection.

    Hi guys
    As you may be aware, based on my other thread here. I'm designing a card game in Java. I was hoping for some advice on the best practise on how methods should be called on a custom Object contained within a custom Collection.
    I have an instance variable for the Deck class as follows: List<Card> deckWhen creating an instance of the class I use deck = new ArrayList<Card>();So I have a Deck which only holds Card objects. My question is, for the Card methods, should I call them on the Card objects after 'getting' the Cards from the Deck or should I write methods within the Deck class which handles this method calling. Code explanation is as follows:
    Deck standardDeck = new Deck();I want to retrieve the suit value of a card within the deck. Is this the best way to do it this way:
    standardDeck.getCardAt(50).getSuit();
    //getCardAt is a method within the Deck class, getSuit() is a method within the Card classor this way:
    standardDeck.getSuitForCardAt(50);
    //getSuitForCardAt() is a method within the Deck class. This method calls the getSuit() method within its method body.Cheers for any help guys.
    Edited by: Faz_86 on Jul 10, 2010 9:53 AM

    Hey Saish
    Thanks for the response.
    My Card class does indeed override hashCode(), equals() and toString().
    The reason I am asking a card from the deck for its Suit is simply because of the rules of the game being played. The game I made is a 'Card Shredding' game where a player attempts to remove as many cards from their hand during each turn. The first to remove all their cards is the winner.
    When the game starts, two decks are created. A standard 52 card deck and an empty deck. Then 8 cards are dealt to each player and one card is dealt into the empty deck. The suit and value of the card on the empty deck called the 'shredding deck' dictates which moves are valid during each turn; The played card must match the Suit or the Value of the current card on the 'shredding deck'
    For example:
    Card on the empty deck = 8 of Spades
    The only card from a players hand which can be removed are any Spade or an Eight of any suit.
    Going back to the Deck.getSuitOfCardAtIndex(int index) , this method is needed because both the AI player and human player need to have the ability to take a look at the cards which have been added to the 'shredding deck'. Again this is because of the rules of the game. Therefore I need a method to take a look at the Suit and Value for any card in the 'shredding deck'.
    Taking all this into account, so far I have the following in my Deck class. Please comment on my design so far. As you can see I've tried to follow the Law Of Demter by creating many little wrapper methods. I understand totally wh getters and setters are bad but I cannot come up with a design solution to achieve what I need to based on the rules of the game without users getters. - Any tips on this would be great.
         public Card dealCard()
              Card cardToDeal = deck.remove(0);
              return cardToDeal;
         public void addCard(Card usedCard) //This method is used to add 'used' cards to the deck.
              deck.add(usedCard);
         public Card getFaceCard() //Returns the current face up playing card
              Card faceCard = deck.get(deck.size()-1);
              return faceCard;
         public int getFaceCardValue()
              int faceCardValue = deck.get(deck.size()-1).getValue();
              return faceCardValue;
         public int getFaceCardSuit()
              int faceCardSuit = deck.get(deck.size()-1).getSuit();
              return faceCardSuit;
         public String getFaceCardName()
              String faceCardName = deck.get(deck.size()-1).toString();
              return faceCardName;
         public Card getCardAt(int position) //Returns the current face up playing card
              Card card = deck.get(position);
              return card;
         public int getFaceCardValueAt(int position)
              int cardValue = deck.get(position).getValue();
              return cardValue;
         public int getFaceCardSuitAt(int position)
              int cardSuit = deck.get(position).getSuit();
              return cardSuit;
         public String getFaceCardNameAt(int position)
              String cardName = deck.get(position).toString();
              return cardName;
         public int getDeckSize() //When recycling cards, the size of the deck is needed to determine the best time to add more cards.
              return deck.size();
         }

Maybe you are looking for

  • How to use Terminal with KeySpan USB serial adaptor cable?

    I own a KeySpan model USA-19HS to use with our MacBookPro when working on clients networking equipment that require serial communication. I have used ZTerm with excellent luck, but it costs, and is yet another application that I dont really want. I w

  • MBP to TV (What TV + adapter to get?)

    I'm in the market for a new TV (and DVD player) and thinking about using my MBP as the DVD player. There is a DVI to S-video adapter ($19) that would work but I don't know how good of quality that would be. Most TVs don't seem to have a DVI input...a

  • GP login script causes windows to crash

    We have a script that runs on all computers that opens our intranet. This script crashed Windows build 9926 overtime. Is there any way to fix this. Also I can't install the new build because the HP printers update fails everytime.

  • Horizontal bars through entire frame

    I've been experiencing this problem more and more. I shoot and edit DV and DVCam (PD150 & DSR20). Sometimes, when I playback the tapes in the deck I get large horizontal bars through the frame (see still sample here) http://www.video11.com/badvideo.j

  • Help w/Sum column

    The following query will return the last 10 records of a table where the record date falls within the first and last of the current month: <pre> SELECT * FROM ( SELECT p_id, f2, amount, date1 FROM mytable a WHERE a.date1 BETWEEN TRUNC(SYSDATE,'MM') A