Getting return value of a method in an interface

Hello! I have a problem. I have an interface called I. One of the declared method in this interface is M. And I have a class called C. Class C declares Interface I. I want to get the return value of the method M. I used invoke method. M.invoke(anInstance, arg[]). You can't take the instance of interfaces or abstract classes. If I use a class instead of instance for anInstance variable, i get "java.lang.IllegalArgumentException: object is not an instance of declaring class" error. If I use an instance, i get "java.lang.IllegalAccessException: Can not call newInstance() on the Class for java.lang.Class" error. This is because of getting an instance of an interface. if you can help me. i will be greatfully happy.

Thanks for the feedback Tom although you should rethink what you said.
I did not trash your suggestion, nor did I make any reference to it.
Perhaps you should read the OP to see where you went wrong.
OP wants to know return type of Interface's methodNo, the OP wants to obtain the return value.
AND OP knows that instantiation won't work.He was trying to instantiate an Interface, which is not possible. In order for him invoke a Method he needs a concrete implementation. I was simply pointing out what he needs to do in order to acheive his aim.
b) there may be no known implementing classes at
runtimeIf there is no implementing class provided then he will not be able to invoke a method on its instance.
c) even if there were such a class, instantiating it
may have unwanted side effects, takes unnecessary
timeWhy is that a problem? One reason for invoking M is to see what happens.
the class may have N methods while the interface
has only one, so you might look for the correct method
too longIf you bothered to study the code I supplied I obtain a Method from the Interface class so there is no problem in "looking" for a method, besides which there can be exactly 1 method with a given signature in any class so there is no searching involved.
On a personal note, such negative replies are neither helpful to the OP and can cause a credibility problem caused by being labelled a Troll.

Similar Messages

  • How to get return value from Java runtime.getRuntime.exec?

    I'm running shell commands from an Oracle db (11gr2) on aix.
    But, I would like to get a return value from a shell comand... like you get with "echo $?"
    I use a code like
    CREATE OR REPLACE JAVA SOURCE NAMED common."Host" AS
    import java.io.*;
    public class Host {
      public static int executeCommand(String command) {
        int retval=0;
        try {
            String[] finalCommand;
            finalCommand = new String[3];
            finalCommand[0] = "/bin/sh";
            finalCommand[1] = "-c";
            finalCommand[2] = command;
          final Process pr = Runtime.getRuntime().exec(finalCommand);
          pr.waitFor();
       catch (Exception ex) {
          System.out.println(ex.getLocalizedMessage());
          retval=-1;
        return retval;
    /but I do not get a return value... because I don't know how to get return value..
    Edited by: user9158455 on 22-Sep-2010 07:33

    Hi,
    Have your tried pr.exitValue() ?
    I think you also need a finally block that destroys the subprocess
    Regards
    Peter

  • Remote Object - not able to get the returned value from java method

         Hi ,
    I am developing one sample flex aplication that connects to the java code and displays the returned value from the
    java method in flex client. Here I am able to invoke the java method but not able to collect the returned value.
    lastResult is giving null .  I am able to see the sysout messages in server console.
    I am using flex 3.2 and blazeds server  and java 1.5
    Here is the code what I have written.
    <?xml version="1.0" encoding="utf-8"?><mx:WindowedApplication  xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="#FFFFFF" initialize="initApp()">
     <mx:Script><![CDATA[
    import mx.controls.Alert; 
    import mx.binding.utils.ChangeWatcher; 
    import mx.rpc.events.ResultEvent; 
    import mx.messaging.*; 
    import mx.messaging.channels.* 
    public function initApp():void { 
         var cs:ChannelSet = new ChannelSet(); 
         var customChannel:Channel = new AMFChannel("my-amf", "http://localhost:8400/blazeds/messagebroker/amf");     cs.addChannel(customChannel);
         remoteObj.channelSet = cs;
    public function writeToConsole():void {      remoteObj.writeToConsole(
    "hello from Flash client");
          var returnedVal:String = remoteObj.setName().lastResult;     Alert.show(returnedVal);
    //[Bindable] 
    // private var returnedVal:String; 
    ]]>
    </mx:Script>
    <mx:RemoteObject id="remoteObj" destination="sro" /> 
    <mx:Form width="437" height="281">
     <mx:FormItem>  
    </mx:FormItem>  
    <mx:Button label="Write To Server Console" click="writeToConsole()"/>
     </mx:Form>
     </mx:WindowedApplication>
    Java code
    public  
         public SimpleRemoteObject(){  
              super();     }
      class SimpleRemoteObject { 
         public void writeToConsole(String msg) {          System.out.println("SimpleRemoteObject.write: " + msg);     }
         public String setName(){          System.
    out.println("Name changed in Java"); 
              return "Name changed in Java";
    And I have configured destination in  remote-config.xml
    <destination id="sro">
       <properties>    
        <source>SimpleRemoteObject</source>
        <scope>application</scope>
       </properties>
      </destination>
    Please help me .

    You are not able to get the returned value because if you see the Remote object help you will realise you have to use result="resultfn()" and fault = "faultfn()"
    In this you define what you wish to do.
    More importantly in the remote object you need to define which method you wish to call using the method class like this
    <mx:RemoteObject id="remoteObj" destination="sro" result="r1" fault="f1"  >
         <Method name="javaMethodName" result="r2" fault="f2"/>
    <mx:RemoteObject>
    r2 is the function where you get the result back from java and can use it to send the alert.

  • How to get the return value of a method

    hi there
    here is the code i write a method
    public void time(int x,int y){
    int xx;
    int yy;
    xx++;
    yy++;
    x=xx;
    y=yy;
    i want to use the return value of x and y at another place,who can tell if it is possible. thank u very much

    You declare the return type of the method, and then use the return keyword to return a value which you can assign to a variable.
    As the other respondent said, you cannot return more than one value from a function. If you need to return two related values, you may want to enclose them in a class and return an instance of that class. For instance:
    class TimeValue {
       final int x;
       final int y;
    public TimeValue(int x, int y) {
       this.x = x;
       this.y = y;
    }Then your method could create a new TimeValues and return it:
    public TimeValue time(int x,int y){
       int xx = x;
       int yy = y;
       ++xx;
       ++yy;
       return new TimeValue(xx, yy);
    }

  • NEED HELP on returning values from a method

    Hello Java World,
    Does anyone know how to return more then 1 value from a method..
    ex.
    //the following returns one value
    //Person Class
    private String getname()
    return this.name;
    how can i get two values (ex. name and occupation of person)
    Thank you in advance.

    Create a Class which will hold the values you want and return that object. Or return a List, or return an array, or - taking your example with the person, why don't you return the whole person object?
    Thomas

  • The problem of return value from a method

    Hi everyone:
    I want return a value from following method. The basic idea is that I want use Num as a parameter to get a value from a field, therefore I can input this value into another database for the display purpose by using other classes. However I got error message when I compiled it.
    "method does not return a value"
    I know it is a problem, but how I can fix it? I need your help. Thanks in advance.
    Dawei
    Method:
    public int Read(int Num) {
    try{
    String qr1 = "select Record form Buffer where Record="+Num+"";
    ResultSet rs = statement.executeQuery(qr1);
    while (!rs.next()){
              int result=rs.getInt(1);
    return(result);
         catch (SQLException e){
                   System.err.println("Error in inserting into database " + e);
                        System.exit(1);
    return 1;

    "select Record form Buffer ...Hopefully "form" is actually "from" in your code.
    You have three points of exit from your routine, and only two return value statements.
    1 -Return inside the while loop has a value.
    2- Return inside the exception block (not sure that '1' would be a valid number)
    3- The very end of the method, just before the last '}' does not have a return statement.
    By the way, this question has nothing to do with JDBC, so another forum might be a better place to post it.

  • Getting return value from webengine.executescript when embedded in Swing

    Hi,
    Got a WebView embedded through a JFXPanel in a Swing app. I'm now trying to get some value back from the WebEngine.executeScript method in a synchronous way.
    All examples I can find on Swing embedding use Platform.runLater, which of course doesn't return the value straight away.
    Through some digging I found PlatformImpl.runAndWait(Runnable) and when I use that I do get a synchronous call and thus the return value of Webengine.executeScript immediately.
    Question now is if it's save for me to use PlatformImpl.runAndWait(Runnable) or if I should refrain from using it for some reason. I wasn't able to find anything on the topic, but so far in my tests if seems to work fine.
    Only thing I found were 2 implementations of sort of the same functionality: http://www.guigarage.com/2013/01/invokeandwait-for-javafx/ and https://code.google.com/p/jacp/source/browse/branches/working/JACP.JavaFX/src/main/java/org/jacp/javafx/rcp/worker/AFXComponentWorker.java (invokeOnFXThreadAndWait method)
    TIA,
    K.

    Using the impl method for run and wait is not advised as it may be removed in a future JavaFX version.
    However you can easily copy the source of this simple method to create your own implementation:
    See the following thread for details:
    http://markmail.org/message/kaui2t34ufx3vdwe
    Note that in making what is normally an asynchronous call synchronous, you must be careful to avoid deadlock and UI freezing performance issues.

  • How to get return values from task flow in af:region ?

    Hi!
    I'm working with a taskFlow that is rendered inside a popup using the "popup inside a region pattern" (http://www.oracle.com/technology/products/adf/patterns/popupregionpattern.pdf), but now this taskFlow has an input parameter and a return value definition. So the question is how to get a value returned by this taskFlow thas is called inside a region?
    Any suggestion?
    Thanks in advance!

    Hi,
    write the value to a shared memory scope like session and read it in the regionNavigation listener. If you follow the paper you refer to then the listener determines of the viewId is null, this a return happens. It wuld then look in the memory scope for the return value.
    Another option would be to use an object that you pass as an argument to the task flow you open in the popup. Then you change the object you passed in, which then makes the return information available in teh calling flow. The object you pass in would have to be in a shared scope too
    Frank

  • How to get return value from java and read by other application?

    i want to read return value from java and the other application read it.
    for example:
    public class test_return {
        test_return(){
        public int check(){
            return 1;
        public static void main(String args[]){
           new test_return().check();
    }from that class i make as jar file. How to read the return value (1) by other application?
    thx..

    If your installer is requiring some process it invokes to return a particular value on failure, then the installer is seriously broken. There are a bazillion commands your installer could invoke, and any of them could fail, which in turn could invalidate the entire install process, and any of them could return any value on failure. The only value that's consistent (in my experience) is that zero means success and non-zero means failure, with specific non-zero values being different in different programs.
    About the only control you have over the JVM's exit code is that if your main method completes without throwing an exception, the JVM will have an exit code of 0, and if main throws an exception (either explicitly or by not catching one thrown from below), it will be non-zero. I'm not even sure if that's guaranteed, but I would guess that's the case.
    EDIT: I'm kind of full of crap here. If you're writing the Java code, you can call System.exit(whatever). But nonetheless, if your installer requires certain exit codes from any app--java or otherwise--you have a problem.
    Edited by: jverd on Oct 29, 2009 1:27 AM

  • Get returned value of a stored procedure

    if a stored procedure ends with the following:
    select "status"=1 or simply select 1 or return 1
    how do I get the value in the call of the jsp page?
    Thanks

    DO NEVER EVER CALL YOUR DATABASE FROM A JSP!
    Have a servlet to call a class that gathers and
    processes the data, and that gives you a value
    object.
    public class Row {
    public final int key;
    public final String status;
    public final String name;
    public final Date timestamp;
    // ... and so forth.
    Row(int i, string s, String n, Date t ...) {
    }An instance of this immutably represents a row of
    data. Return this to the servlet, have the servlet
    add it to the session and retrieve it again in your
    JSP:
    <td>status: </td><td><%= myDataObject.status
    %></td>
    Right on. This is the most common malpractice I ahve come across. Accessing the database from with in a jsp is violation of seperation of concerns as well as MVC. Not only would I suggest using a servlet but I would add use the servlet as a controller and for rest use beans and model code.

  • How to get return values from stored procedure to ssis packge?

    Hi,
    I need returnn values from my stored procedure to ssis package -
    My procedure look like  and ssis package .Kindly help me to oget returnn value to my ssis package
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author: <Author,,Name>
    -- Create date: <Create Date,,>
    -- Description: <Description,,>
    -- =============================================
    ALTER PROCEDURE [TSC]
    -- Add the parameters for the stored procedure here
    @P_STAGE VARCHAR(2000)
    AS
    BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    -- Insert statements for procedure here
    --SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
    truncate table [INPUTS];
    INSERT
    INTO
    [INPUTS_BASE]
    SELECT
    [COLUMN]
    FROM [INPUTS];
    RETURN
    END
    and i am trying to get the return value from execute sql task and shown below
    and i am taking my returnn value to result set variable

    You need to have either OUTPUT parameters or use RETURN statement to return a value in stored procedures. RETURN can only return integer values whereas OUTPUT parameters can be of any type
    First modify your procedure to define return value or OUTPUT parameter based on requirement
    for details see
    http://www.sqlteam.com/article/stored-procedures-returning-data
    Once that is done in SSIS call sp from Execute SQL Task and in parameter mapping tabe shown above add required parameters and map them to variables created in SSIS and select Direction as Output or Return Value based on what option you used in your
    procedure.
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How to get return values from region?

    I add a page flow as region into a page. The page flow has a return parameter. How to get the return value in parent page?

    I have been also intrigued by this question.
    There is however a workaround that you can set the values in requestScope.
    We can have a regionNavigationListener on the region and catch the end of taskflow if viewid is null.
    regionNavigationEvent.getNewViewId() == null
    Here we can read the request values and set wherever to be used.
    maniesh (sid)

  • Error getting return value from function

    Hello
    I'm getting a error calling a function with ODP.NET from C#
    Code:
    OracleCommand oraCom = new OracleCommand("NORMALIZACION.nif",oraCon);
    oraCom.CommandType = CommandType.StoredProcedure;
    OracleParameter param1 = new OracleParameter("numnif",OracleDbType.Varchar2);
    param1.Value= "73667866A";
    param1.Direction = ParameterDirection.Input;
    OracleParameter param2 = new OracleParameter("nif",OracleDbType.Varchar2);
    param2.Size = 10; //FIXME line
    param2.Direction = ParameterDirection.ReturnValue;
    oraCom.Parameters.Add(param1);
    oraCom.Parameters.Add(param2);
    oraCom.ExecuteNonQuery();
    nif_norm = oraCom.Parameters["nif"].Value.ToString();
    if i write the FIXME line i get a error (ORA-06502) complaining about the size, no matter the value i wrote.
    If i don't write the FIXME line, it works but nif_norm is always empty, although the function i call is a single return 'Hello';
    Where am I wrong??
    Any help, examples with varchar2 as return value???
    BTW: the same code with the MS provider for Oracle works fine.

    Good point -- i shall do so.
    What I think I'm missing, in my quest for ODP.NET competence, is a solid set of example code. I've searched around and found various fragements here and there, but when it comes to data access from .NET there must surely be some finitie set of possibilities (if we can discount bad practices like building dynamic SQL statements without bind variables).
    For example, possibly in increasing order of complexity ...
    * Read a single value from a SQL statement ... "select emp_name from emp where rownum < 2"
    * Read a single value by passing in a parameter ... "select emp_name from emp where user_id = :?"
    * read multiple values ... "select emp_name from emp where user_id in (:?,:?)"
    * execute a stored procedure with no in or out parameters
    * retreive a value from a function with no parameters
    * pass a parameter to a stored procedure
    * read an out parameter from a stored procedure
    Then work with in and out ref cursors, blobs, whatever.
    Thoughts?

  • Getting Return values from RFC function call with visual basic

    Hi,
    I am creating a sample app to connect to a SAP system which call its RFC functions created with ABAP. It was known that the function will return more than 1 return values.
       SAP Function name ==> "ZFMTP_RFC_GET_RESULT"
            Export parameters (to SAP):
                    - Student Name [char 10]         ==> "STUNAME"
                    - Student ID         [char 20]        ==> "STUID"
           Return values (From SAP):
                    - Results [char 10]        ==> "RESULT"
                    - Remarks [char 200]        ==> "REMARKS"
    i have managed to get sample codes for connecting and call a RFC function with vb but they only get a return value. How do i retrieve multiple return values like the above function "RESULT" and "REMARKS"?
    Here's my vb code to accessing the function
            Dim R3 As Object
            Dim FBFunc As Object
            Dim returnFunc As Boolean
            Dim connected As Boolean
            R3 = CreateObject("SAP.Functions")
            R3.Connection.Client = "000"
            R3.Connection.User = "BCUSER"
            R3.Connection.Password = "minisap"
            R3.Connection.Language = "DE"
            R3.Connection.System = "dtsystem"
            R3.Connection.Applicationserver = "xxx.xxx.xxx.xxx" 
            connected = R3.Connection.Logon(0, True)
            If connected <> True Then
                MsgBox("Unable to connect to SAP")
            End If
            FBFunc = R3.add("ZFMTP_RFC_GET_RESULT")
            FBFunc.exports("STUNAME") = "Jonny"
            FBFunc.exports("STUID") = "12345"
            returnFunc = FBFunc.Call() <<== How do i get the return value? or RESULT and REMARKS of the RFC Function?
    thanks alot.
    Edited by: Eugene Tan on Mar 4, 2008 7:17 AM

    Hi Gregor,
    Thanks for the link....i am having some doubts with the codes, hope you can clarify them for me if you know the codes..
    Below is the code snippet.
    Set impReturn = CHPASS_FN.Imports("RETURN")  <<=== is RETURN the standard keyword to get a                                                                                return object?
      expPassword.Value = currpass
      expNewPass.Value = newpass
      expFillRet.Value = "1"
    ''' Call change password function
      If CHPASS_FN.Call = True Then
        outFile.Write (", Called Function")
        Message = impReturn("MESSAGE") <<==== So if i have 3 return values..i just replace with the return                                                               value variable names?
        outFile.WriteLine " : " & Message
      Else
        outFile.Write (", Call to function failed")
      End If
    thanks alot...all your help is very appreciated.

  • How to know that a method has been called and returning value of a method

    Hi, everyone! I have two questions. One is about making judgment about whether a method has been called or not; another one is about how to return "String value+newline character+String value" with a return statement.
    Here are the two original problems that I tried to solve.
    Write a class definition of a class named 'Value' with the following:
    a boolean instance variable named 'modified', initialized to false
    an integer instance variable named 'val'
    a constructor accepting a single paramter whose value is assigned to the instance variable 'val'
    a method 'getVal' that returns the current value of the instance variable 'val'
    a method 'setVal' that accepts a single parameter, assigns its value to 'val', and sets the 'modified' instance variable to true, and
    a boolean method, 'wasModified' that returns true if setVal was ever called.
    And I wrote my code this way:
    public class Value
    boolean modified=false;
    int val;
    public Value(int x)
    {val=x;}
      public int getVal()
      {return val;}
       public void setVal(int y)
        val = y;
        modified = true;
         public boolean wasModified()
          if(val==y&&modified==true)
          return true;
    }I tried to let the "wasModified" method know that the "setVal" has been called by writing:
    if(val==y&&modified==true)
    or
    if(x.setVal(y))
    I supposed that only when the "setVal" is called, the "modified" variable will be true(it's false by default) and val=y, don't either of this two conditions can prove that the method "setVal" has been called?
    I also have some questions about the feedback I got
    class Value is public, should be declared in a file named Value.java
    public class Value
    cannot find symbol
    symbol  : variable y
    location: class Value
    if(val==y&&modified==true)
    *^*
    *2 errors*
    I gave the class a name Value, doesn't that mean the class has been declared in a file named Value.java*?
    I have declared the variable y, why the compiler cann't find it? is it because y has been out of scale?
    The other problem is:
    Write a class named  Book containing:
    Two instance variables named  title and  author of type String.
    A constructor that accepts two String parameters. The value of the first is used to initialize the value of  title and the value of the second is used to initialize  author .
    A method named  toString that accepts no parameters.  toString returns a String consisting of the value of  title , followed by a newline character, followed by the value of  author .
    And this is my response:
    public class Book
    String title;
    String author;
      public Book(String x, String y)
       { title=x; author=y; }
       public String toString()
       {return title;
        return author;
    }I want to know that is it ok to have two return statements in a single method? Because when I add the return author; to the method toString, the compiler returns a complain which says it's an unreachable statement.
    Thank you very much!

    Lets take this slow and easy. First of all, you need to learn how to format your code for readability. Read and take to heart
    {color:0000ff}http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html{color}
    Now as to your first exercise, most of it is OK but not this:   public boolean wasModified()
          if (val == y && modified == true)
                return true;
    y being a parmeter to the setValue method exists only within the scope of that method. And why would you want to test that anyways? If modified evaluates to true, that's all you need to know that the value has been modified. So you could have   public boolean wasModified()
          if (modified == true)
                return true;
       }But even that is unnecessarily verbose, as the if condition evaluates to true, and the same is returned. So in the final analysis, all you need is   public boolean wasModified()
          return modified;
       }And a public class has to be declared in a file named for the class, yes.
    As for your second assignment, NO you cannot "return" two variables fom a method. return means just that: when the return statement is encountered, control returns to the calling routine. That's why the compiler is complaining that the statement following the (first) return statement is unreachable.
    Do you know how to string Strings together? (it's called concatenation.) And how to represent a newline in a String literal?
    db

Maybe you are looking for

  • Free sample sales - Control for Total Value

    Dear all, In our sales free process we configured a condition type Z100 Net value and condition record maintained with Key Customer / Material / Plant Higher authority is maintaining teh condition reocrd for one day. 10000/ Fg123456 / h210 - 100 % 12

  • Steps to upgrade RAC wit Standby Database ?

    Hi All I have RAC environment with 8 Nodes (Linux 4) , I have one node as physical standby for this RAC. My oracle is 10.2.0.3 , and i want to update it to 10.2.0.5 Could you please advice me with steps , when i Google i found that i have to start wi

  • What Do I Need To Run A External Moniter with a Macbook Pro?

    I have a Mac Book Pro 13in Mid 2009 Model. I replaced the RAM to 8GB, I have an HDMI Converter cable to plug my mac book into my 21in moniter, but it seems like it is still lagging behind, with internet connection but the screen just cant keep up or

  • Hp mini 210- forgot password

    Hi i forgot my password for my HP mini 210. any help wil be appreciated. Thanks

  • Using image from camera as wallpaper

    Hi! I just received the Z3 compact, after having "upgraded" from the Galaxy S3. As I have a little son, I often use pictures of him as a wallpaper. On the Galaxy S3 this was piece of cake, just press "use as" and it would fix everything. On the Z3 co