Passing a Method into a Constructor!!!

Hi:
I am new to Java Programming. Can some one explain me how to pass a Method into a Constructor? Any help is appreciated.
Thank you in advance.

If you are new to Java I suggest you learn more about Java before asking questions like that. It is possible to do that, but you probably didn't mean what you said.

Similar Messages

  • Passing generics into a constructor.

    Hi
    I have this class as follows.
    package generation;
    import java.util.LinkedList;
    import java.util.NoSuchElementException;
    import java.util.Queue;
    @author David
    *public class EconomicLoadOrder<E>*
    *Queue<E> queue = new LinkedList<E>();*
    *public EconomicLoadOrder()*
    *//Empty constructory*
    *public void addGenerator(E gen)*
    *this.queue.add(gen);*
    *public E getNextGenerator() throws NoSuchElementException*
    *return this.queue.remove();*
    Now I instantiate an instance of this class in this main
    *package powerreliability;*
    *import generation.CapacityOutage;*
    *import generation.EconomicLoadOrder;*
    *import generation.Generator;*
    @author David
    *public class Main {*
    *@param args the command line arguments*
    public static void main(String[] args)
    //Initialise the first
    Generator gen1 = new Generator("gen1", 40, 0.05);
    EconomicLoadOrder<Generator> economicLoadOrder = new EconomicLoadOrder<Generator>();
    economicLoadOrder.addGenerator(gen1);
    CapacityOutage capacityOutage = new CapacityOutage(economicLoadOrder);
    capacityOutage.computeCapacityOutage();
    }and I get an error in this class when I pass the instance into the constructor.
    package generation;
    import java.util.NoSuchElementException;
    @author David
    public class CapacityOutage<T> {
    private EconomicLoadOrder<Generator> economicLoadOrder;
    public CapacityOutage(T t)
    {color:#ff0000}this.economicLoadOrder = t;{color}
    public void computeCapacityOutage()
    try
    Generator gen = this.economicLoadOrder.getNextGenerator();
    catch(NoSuchElementException e)
    // do nothing for now.
    }Now where I have coloured it red, I get a red underline indicating an error saying that they are icompatible types.
    The two types being T and EconomicLoadOrder.
    When I cast the t, it works though. i'm not sure if this is the correct usage though. I thought generics are supposed to save you from casting. is it alright, correct to cast this, or can I fix this problem without casting?
    Thanks

    In the first code description, please ignore the green commented out code. In the real file this code is not commented out and it is actually functional code in my file. Otherwise the file wouldn't work. i.e. in my ide, this code isn't commented out. Something happened while I was putting it into this forum window.
    cheers.

  • Project PSI API checkoutproject is causing exception :LastError=CICOCheckedOutToOtherUser Instructions: Pass this into PSClientError constructor to access all error information

    Hi,
    I'm trying to add a value to the project custom field. After that I'm calling the checkout function before the queueupdate and queuepublish. While calling the checkout  the program is throwing exception as follow:
    The exception is as follows: ProjectServerError(s) LastError=CICOCheckedOutToOtherUser Instructions: Pass this into PSClientError constructor to access all error information
    Please help me to resolve this issue.  I have also tried the ReaProjectentity method i nthe PSI service inrodr to find that project is checked out or not  . Still  the issue is remains . Anyone please help me for this
    flagCheckout = IsProjectCheckedOut(myProjectId);
                        if (!flagCheckout)
                            eventLog.WriteEntry("Inside the updatedata== true and value of the checkout is " + flagCheckout);
                            projectClient.CheckOutProject(myProjectId, sessionId, "custom field update checkout");
    Regards,
    Sabitha

    Standard Information:PSI Entry Point:
    Project User: Service account
    Correlation Id: 7ded1694-35d9-487d-bc1b-c2e8557a2170
    PWA Site URL: httpservername.name/PWA
    SSP Name: Project Server Service Application
    PSError: GeneralQueueCorrelationBlocked (26005)
    Operation could not completed since the Queue Correlated Job Group is blocked. Correlated Job Group ID is: a9dda7f4-fc78-4b6f-ace6-13dddcf784c5. The job ID of the affected job is: 7768f60d-5fe8-4184-b80d-cbab271e38e1. The job type of the affected job is:
    ProjectCheckIn. You can recover from the situation by unblocking or cancelling the blocked job. To do that, go to PWA, navigate to 'Server Settings -> Manage Queue Jobs', go to 'Filter Type' section, choose 'By ID', enter the 'Job Group ID' mentioned in
    this error and click the 'Refresh Status' button at the bottom of the page. In the resulting set of jobs, click on the 'Error' column link to see more details about why the job has failed and blocked the Correlated Job Group. For more troubleshooting you can
    look at the trace log also. Once you have corrected the cause of the error, select the affected job and click on the 'Retry Jobs' or 'Cancel Jobs' button at the bottom of the page.
    This is the error I'm getting now while currently calling the forcehckin, checkout and update. Earlier it was not logging any errors.From this I'm not able to resolve as i cannot filter with job guid

  • How to call a java method so I can pass a file into the method

    I want to pass a file into a java method method from the main method. Can anyone give me some help as to how I pass the file into the method - do I pass the file name ? are there any special points I need to put in the methods signature etc ?
    FileReader file = new FileReader("Scores");
    BufferedReader infile = new BufferedReader(file);
    Where am I supposed to put the above text - in the main method or the one I want to pass the file into to?
    Thanks

    It's a matter of personal preference really. I would encapsulate all of the file-parsing logic in a separate class that implements an interface so that if in the future you want to start taking the integers from another source, e.g. a db, you wouldn't need to drastically alter your main application code. Probably something like this, (with an assumption that the numbers are delimited by a comma and a realisation that my file-handling routine sucks):
    public class MyApp{
    public static void main(String[] args){
    IntegerGather g = new FileIntegerGatherer();
    Integer[] result = g.getIntegers(args[0]);
    public interface IntegerGatherer{
    public Integer[] getIntegers(String location);
    import java.io.*;
    public class FileIntegerGatherer implements IntegerGatherer{
    public Integer[] getIntegers(String location){
    FileInputStream fs=null;
    try{
    File f = new File(location);
    fs = new FileInputStream(f);
    byte[] in = new byte[1024];
    StringBuffer sb = new StringBuffer();
    while((fs.read(in))!=-1){
    sb.append(new String(in));
    StringTokenizer st = new StringTokenizer(sb.toString(),",");
    Integer[] result = new Integer[st.countTokens()];
    int count = 0;
    while(st.hasMoreTokens()){
    result[count]=Integer.valueOf(st.nextToken());
    count++;
    catch(IOException e){
    //something sensible here
    finally{
    if(fs!=null){
    try{
    fs.close();
    catch(IOException f){
    return result;
    Once compiled you could invoke it as java MyApp c:\myInts.txt
    Sorry if there are typos in there, I don't have an ide open ;->

  • How to pass a file into a java method

    I am trying to pass a file into a java method so I can read the file from inside the method. How can I do this? I am confident passing int, char, arrays etc into methods as I know how to identify them in a methods signature but I have no idea how to decalre a file in a mthods signature. Any ideas please ?
    Thanks

    Hi,
    Just go thru the URL,
    http://www6.software.ibm.com/devtools/news1001/art24.htm#toc2
    I hope you will get a fair understanding of 'what is pass by reference/value'.
    You can pass Object reference as an argument.
    What Pablo Lucien had written is right. But the ideal situation is if you are not modifying the
    file in the calling method, then you can pass the String (file name) as an argument to the called method.
    Sudha

  • Pass an arrayList into a method

    I am looking to pass and  arraylist into a method and I am wondering how this is done...

    I figured it out:
    public function someMethod(someArray:ArrayList){}
    I figured it was the same.
    This is dealing with flex, How ever on the AS side, so its a pure AS question

  • How to pass a variable into a cfc?

    prior to calling the cfinvoke, I have coding that determins a
    variable "X"
    I need to pass X into a cfc so it can complete the query held
    there.
    So I tried
    <cfinvoke component="A"
    method="AList"
    returnvariable="AResults">
    <cfinvokeargument name="x" value="#X#"
    /></cfinvoke>
    correct so far?
    Now over on the cfc page is where I'm getting stuck
    Inside my cffunction I'm adding <cfargument name="X" />
    But how do I get the value in?

    I don't quite understand your question. Can you rephrase?
    But before all that, bear in mind that one doesn't pass a
    variables into a
    *CFC*, one passes it into a function within the CFC. And as
    with all
    functions, one passes values into the function by passing it
    as an
    argument. But - of course - the function has to be coded to
    expect the
    argument.
    Your own sample code demonstrates this in action:
    <cfinvokeargument name="abbrCode"
    value="#companyAbbrCode#" />
    (NB: lose the trailing slash: this is CFML, not XML).
    So you know how to do that.
    Hence me not quite understanding what you're actually asking.
    Adam

  • Passing array of parameters to constructor

    I'm writing a script which facilitates interaction between javascript and an already existing flash library. One of the things I need to do is create an instance of class x, where class x can be one of a large number of classes. The constructors for these classes each take different numbers of parameters. I want to pass the parameters in from Javascript as an array, and I was hoping that there would be a way to pass the array contents into the constructor as parameters. I tried using apply, but it's not available on constructors.
    The only other option I know of is to write a large case statement full of constructors, and for each parameter pass an integer indexed array element. Is there any other way?

    Your going to have to unpack your array no matter what, so no.
    You can make your class factory with your huge case, or, if you have the source for your lib you could modify the constructor, but its the same amount of work:
    Was:
    public function MyClass(s:String, n:Number, d:Date){...}
    To:
    public function MyClass(s:*, n:Number=0, d:Date=nul){
      <case code here>
    If you have a decent platform, or even javascript, you could maybe think about writing a parser that will generate the class factory case based on the constructor signatures.

  • Passing a method call to a facelet tag

    Hello,
    I am trying to create a JSF confirmation box that replaces the Javascript confirm() function. I am using Seam and Rich Faces 3.2.1. The confirm box is a facelet tag that pops up a modal box with 'cancel' and a 'continue' buttons. Everything is working correctly except for one crucial piece; passing the method call for continue button.
    Here is the set up for the facelets tag in the main xhtml page:
    <at:confirm
        id="confirm"
        title="Confirm"
        message="Do you want to continue"
        buttonText="Continue"
        backingBean="#{confirmAction}"
        method="testMethodTwo"
    />Here is the code for the button inside the facelets tag:
    <a4j:commandLink
        styleClass="rdSplGr1"
        href="#"
        action="#{backingBean[method]}">
        <s:span>#{buttonText}</s:span>
    </a4j:commandLink>The method simply does nothing when the use clicks the button. I am assuming this is due to the lack of "()" however there does not seem to be a way to get those in there. I have tried the following:
    1) placing the parens like this - method="testMethodTwo()"
    2) placing the parens like this - action="#{backingBean[method]()}"
    The first does nothing, the second causes an EL exception.
    I know that it has nothing to do with the modal as I have also placed a button like this into the modal:
    <a4j:commandLink
        styleClass="rdSplGr1"
        href="#"
        action="#{confirmAction.testMethodOne()}">
         <s:span>MethodOne</s:span>
    </a4j:commandLink>That button as you can see has what I am trying to create dynamically and it works like a charm.
    So how do I pass a method call correctly? Or if that is impossible how do I solve the problem of having a the continue button having a different method assigned to it?
    Thanks for any insight into this.
    Edited by: Rhythmicdevil on Aug 4, 2008 7:57 AM

    I agree, reflection should be a last resort. An
    interface would not be useful if you don't know what
    method you want to invoke at compile time. Interfaces
    are useful when you know the method you want to
    invoke, but not the class.That's not true. This is a really lame-ass example but it shows the point.
    public interface RuntimeMethod
       public void method();
    class AClass {
       public static void main(Sting[] args)
          new AClass.handleAtRuntime(
             Factory.getRuntimeMethod(Integer.parse(args[0])));
       public void handleAtRuntime(RuntimeMethod runtime)
          runtime.method();
    class Factory
       public static getRuntimeMethod(int method)
          switch(method)
             case 0: return new RuntimeMethod
                public void method()
                   methodA();
             case 2: return new RuntimeMethod
                public void method()
                   methodB();
             default:
                throw new IllegalArgumentException("bad input");
    }

  • Passing formatted HTML into JOptionPane.showMessageDialog()

    I'm attempting to display a message dialog that contains text that is formatted as HTML. The examples I've looked up online show that you can indeed create a string that begins with the tag <html> and pass that string into most swing text components.
    Such as:
    String htmlString = "<html><b>This is a bold string</b>";
    JOptionPane.showMessageDialog(htmlString, ...);I want to do the same thing, but have my HTML stored in a seperate file. I tried using file IO to read in the html one line at a time, and append it into a StringBuffer. Then passing my buffer.toString() into showMessageDialog(). ..It's still not showing my HTML (although it does compile fine).
    Before I start digging into this deep, I just wanted to ask if there was a better solution for accomplishing what I'm trying to do here. Perhaps using a different component or something? I appreciate it.

    (shrugs) Both these examples seem to render the HTML OK, the first is a String provided to a JLabel, the second is an URL provided to a JEditorPane. I included the second to show a Swing component rendering HTML from an external source.
    import java.awt.Dimension;
    import javax.swing.JOptionPane;
    import javax.swing.JEditorPane;
    import java.net.URL;
    class TestHtmlRendering {
      public static void main(String[] args) throws Exception {
        // default for a String in a JLabel is bold,
        // so let's add some emphasis..
        String content =
          "<html><b>This is a bold, " +
          "<em>emphatic</em> string!</b>";
        JOptionPane.showMessageDialog(null, content);
        // styled HTML from http://pscode.org/test/docload/
        URL url = new URL(
          "http://pscode.org/test/docload/trusted.html");
        JEditorPane jep = new JEditorPane(url);
        jep.setPreferredSize(new Dimension(300,200));
        JOptionPane.showMessageDialog(null, jep);
    }I'd say the problem is in the code you did not show, though even the code you did show, was nonsense (show me the URL to the JavaDocs of any showMessageDialog() method that will accept a String as the first argument). For those reasons (and more), I recommend preparing an SSCCE that shows the problem. It is a little harder to prepare an SSCCE involving external files, though if you can demonstrate it using an URL (like above) that solves the problem.

  • Pass flex val into cfc

    Hi,
    I need example of code I can pass flex var into cfc.
    I mean I created form in coldfusion. I have my cfc.
    I would like to pass form value into cfc using flex. How can
    I do that.
    Thanks

    You can define method inside your cfc components which accept
    parameter.
    <mx:RemoteObject id="remoteService"
    destination="ColdFusion"
    showBusyCursor="true" source="components.simple">
    <mx:method name="getSimpleData" result="onResult(event)"
    fault="onFault(event)" />
    </mx:RemoteObject>
    and call those methods with the arguments.
    public function initApp():void {
    remoteService.getSimpleData(name);
    }

  • How can I pass a value into a page fragment?

    How can I pass a value into a page fragment?
    I am implementing four search screens. And the only thing different about them will be their backing bean.
    So I’d like to do something like have four pages, each which retrieves its appropriate backing bean, sets that bean to a variable, and then includes a page fragment which contains the generic search page code (which will make use of that variable).
    The code in the four pages would be something like this:
    <?xml version='1.0' encoding='windows-1252'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"
    xmlns:c="http://java.sun.com/jsp/jstl/core">
    <jsp:directive.page contentType="text/html;charset=windows-1252"/>
    <c:set var="searchPageBackingBean"
    value="#{pageFlowScope.employeeSearchPageBean}"
    scope="page"/>
    <jsp:include page="./SearchPageBody.jsff"/>
    </jsp:root>
    At this point, what I’m seeing is that the fragment page, SearchPageBody.jsff, has no visibility of the searchPageBackingBean variable, either referencing it as #{pageFlowScope.searchPageBackingBean} or just #{searchPageBackingBean}

    The following will work, assuming you are needing to access a managed bean:
    Put this in the parent page:
    <c:set var="nameOfSearchPageBackingBean"
    value="employeeSearchPageBean"
    scope="request"/>
    Put this in the child, SearchPageBody.jsff:
    <c:set var="searchPageBean"
    value="#{pageFlowScope[nameOfSearchPageBackingBean]}"
    scope="page"/>

  • Calling static synchronized method in the constructor

    Is it ok to do so ?
    (calling a static synchronized method from the constructor of the same class)
    Please advise vis-a-vis pros and cons.
    regards,
    s.giri

    I would take a different take here. Sure you can do it but there are some ramifications from a best practices perspective. f you think of a class as a proper object, then making a method static or not is simple. the static variables and methods belong to the class while the non-static variables and methods belong to the instance.
    a method should be bound to the class (made static) if the method operates on the class's static variables (modifies the class's state). an instance object should not directly modify the state of the class.
    a method should be bound to the instance (made non-static) if it operates on the instance's (non-static) variables.
    you should not modify the state of the class object (the static variables) within the instance (non-static) method - rather, relegate that to the class's methods.
    although it is permitted, i do not access the static methods through an instance object. i only access static methods through the class object for clarity.
    and since the instance variables are not part of the class object itself, the language cannot and does not allow access to non-static variables and methods through the class object's methods.

  • Pass a method as an object to DocumentListener

    So far, I have been assigning document listeners to JTextfields within the same class as the JTextField, as in...
                   private createJTextField(){
                       JTextField t = new JTextField();
                       t.getDocument().addDocumentListener(documentListener());
                   private DocumentListener documentListener() {
                  DocumentListener listener = new DocumentListener(){
                      public void changedUpdate(DocumentEvent e){textFieldActions();}
                  public void removeUpdate(DocumentEvent e){textFieldActions();}
                         public void insertUpdate(DocumentEvent e){textFieldActions();};};
                 return listener;
                private void textFieldActions() {
                  //Do something, like search the text in the JTextField for a string;
                  }This does work, but it means I have to include similar blocks of code for every JTextField I create.
    ...so, I thought it would be better to set up a utility that I could pass the JTextField and method to, which would assign the method to the DocumentListener. Something like...
         private JTextField t;
         private Boolean b;
         private JTextFieldDocumentListenerUtility l;
         protected void setUp(){
              t = new JTextField();
              b = false;
              l = new JTextFieldDocumentListenerUtility();
         public void testDocumentListener(){
              assertFalse(b);
              l.assignAction(t, someAction());
              t.setText("bogus");
              assertTrue(b);
         private void someAction() {
              b = true;
                   }The JTextFieldDocumentListenerUtility class includes the "private DocumentListener documentListener()" method in the first block of code.
    However, I can't pass the method "as is". I think (and I need some guidance here) its because the method "someAction()" returns a void, whereas I need to pass an object to the JTextFieldDocumentListenerUtility.
    What is the tidiest way to do this, given that I'm trying to cut down duplicate code every time I create a JTextField?
    Can someone please walk me through this?

    You could use the Strategy pattern.
    Basically creating a DocumentListener implementation that accepts as parameters the JTextField and a separate "Operation" instance. Where operation would be an
    interface that would define a single operation() method (or 3 different operation methods if you want different operations performed for the changed/remove/insert events).
    Some non-tested sample code.
    public class MyListener implements DocumentListener {
        private JTextField field;
        private Operation operation;
        public MyListener(JTextField field, Operation operation) {
            this.field = field;
            this.operation = operation;
        public void changedUpdate(DocumentEvent e) { operation.changed(field); }
        public void removeUpdate(DocumentEvent e) { operation.remove(field); }
        public void insertUpdate(DocumentEvent e) { operation.insert(field); }
    }This way if you have 10 textfields that need to behave in a similar way, you'd need only create 1 Operation implementation that handles the functionality and just use
    t.getDocument().addDocumentListener(new MyListener(t, new MyStandardOperation()));Since you can't pass around only methods, you need to have a class to contain them in.
    But if you need to have several textfields that have similar functionality, you'll have the functionality contained in a single place and cut down on the boilerplate code.

  • Passing a string into an SQL query IN statement

    Hello,
    I need to connect to a database to pull some data to dynamically create a form based on the data I pull back. My SQL query works fine when I manually run it through a SQL client tool, but when I try to pass it through my workflow I'm having trouble with passing my string into the IN part of the statement. So if for example my SQL query is:
    SELECT Field1, Field2, Field3 FROM Table1 WHERE Field4 IN (?)
    I have a process variable that has the string I'm trying to pass into the ?, but I don't seem to be able to get the query to run. I have tried setting up my query to run as a Parameterized Query (passing my string process variable into the ?), and by setting the query up through xPath (where I am calling my process variable with an xPath declaration), but am not having any luck.
    The process variable I am trying to pass is formatted such that I'm passing 'Value1','Value2','Value3' but I can reformat this string if need be. Even with using test data I can't get the query to return anything. For test data I have tried: 'Value1','Value2','Value3' ; Value1','Value2','Value3 ; Value1,Value2,Value3 but the query never returns any data. I can't seem to see how to format the string to pass into the query. The Query will work with a single Value in the test data, but as soon as I try to pass multiple values within the string it fails. Any suggestions?

    The problem looks to be a limit on what I can pass into the SQL query component. My string is coming from data returned from another database. I take the xml output from that database call, pass it through a set variable component to remove my xml tags from the string, and then format the string in a script component (I have to do it this way because of the way the data coming out of my first database call). I've put in loggers, and can see that the string I'm passing into my query that is giving me problems, is formatted the same way as if I were to use the concat function Scott listed above. It looks like there is a limitation on what can be passed in my variable. I have tried creating my entire SQL query statement in a set variable component, and then just calling the process variable that holds that statement, but there is a character limit of 128 character for what can be passed in a variable through xpath in the SQL query component.
    The next thing I tried was changing my SQL where clause. Instead of passing my variable directly into the IN statement I set up a PATINDEX('%:'+countyname+ ':%', ?) > 0 call to check for the values in my database call. As you can see I took out the "," that I was passing as part of my string, thinking that the SQL component was getting confused by them, and placed ":" characters around my values being passed in my string variable. No matter what I try to do though I'm not able to get the query to run. The component looks like it is taking my string, and is seeing the whole thing as a string instead of passing it as individual values within a string.
    I think I'm getting close, but I keep getting a Content not allowed in prolog exception in the server logs.

Maybe you are looking for

  • ASO Partial clear in Essbase v 9.2.0

    Can anyone let me know how to clear partial data from an Aggregate storage database in Essbase v9.2.0? We are trying to clear some data in our dbase and don't want to clear out all the data. Thank you in Advance, Dan

  • Down payment against PO

    Dears, I have few issues while processing down payments for international vendors. Firstly, we are not able to pay DP for complete PO, system requires line item, the issue is my client wish to pay DP for complete PO because we create PO with more tha

  • Does ipad Australia work in USA/europe etc?

    Will an ipad4/mini bought in australia(240V) operate in Europe(220V) or USA(110V)? I researched through apple that the ipads have an automatic voltage detector in built that converts the voltage as required. Any practical experience with this? Also,

  • Wireless Mighty Mouse Disc

    I left my install disc in a hotel room in San Francisco. I can not find the drivers for the Wireless Mighty Mouse anywhere on Apple's site. Do I have to buy another mouse just to get the drivers? Why doesn't Apple have the option to download them? Am

  • Dell Inspiron 7000 - Dragon Assistant 3.0 Software Missing?

    I purchased a 15.6" Dell Inspiron 7000 Laptop on 1-10-15 and it was supposed to come wiht Dragon Assistant, Voice Recognition Software pre-installed.  It is NOT, however anywhere on this machine.  It is advertised as being on the Laptop - both in the