locked
CSharp Equivalent of java.lang.reflect.Method RRS feed

  • Question

  • Dear All,

    I am looking for the equivalent of java.lang.reflect.Method and found out the solution below

    MethodInfo[] methods = typeof(Class).GetMethods();
    
    // Example 
    foreach (MethodInfo info in methods)
                {
                    Console.WriteLine(info.Name);
    
                    // Call Win method.
                    if (info.Name == "Win")
                    {
                        info.Invoke(program, null); // [2]
                    }
                }

    It is working but don't know it is correct usage or not.

    I hope someone will advise me to get it prove.

    Thanks and best regards

    • Moved by Mike Feng Thursday, February 7, 2013 11:52 AM
    Wednesday, February 6, 2013 7:19 AM

All replies

  • Instead of using a loop over all the methods, you can get the method you want by calling GetMethod with the name of the method (as in Java).

    You can also directly invoke the method by using InvokeMember.

    • Proposed as answer by Mike Feng Thursday, February 7, 2013 11:52 AM
    Wednesday, February 6, 2013 7:48 AM
  • Hi All,

    Here is my java code

    // in Java
    
    
    Class A
    {
    
    }
    
    Class B
    {
    
    }
    
    
    Class Test
    {
       A a = new A();
       B b = new B();
    
       int len;
       int data;
    
       public static Test Do
       {
        java.lang.Class<?> mclass=null;
        String test = "Test";
       
    
        java.lang.reflect.Method mth = mclass.getDeclaredMethod(test, A.class, int.class, int.class);            // How can I do in .NET
       
        newA = (A) mth.invoke(null, b, len, data);   // How can I do in .NET
    
       }
    }
        
    
         

    Here is my CSharp

    // in CSharp
    
    Class A
    {
    
    }
    
    Class B
    {
    
    }
    
    
    Class Test
    {
       A a = new A();
       B b = new B();
       A newA = new A();
    
       int len;
       int data;
    
       public static Test Do
       {
        Type mclass = null;
        String test = "Test";
       
        MethodInfo[] mth = typeof(A).GetMethods();   
       
        newA = (A) ?(null, b, len, data);   // How can I do in .NET
    
       }
    }
        
    

    I hope someone will advise me to get it done.

    Thanks and best regards


    Friday, February 8, 2013 5:16 AM
  • Hi,

    My first suggestion is to read about c# carefully. That way you can learn everything much better.

    My seccond suggestion is to not translate code 1:1 from java to c#. Rewrite the code in C# - maybe you want to do some things different in C#.

    <snd regarding your code: I simply do not understand what your java code is doing. You create 2 empty classes A and B?

    I would think that you get a methof Test which returns a reference to A and takes 2 arguments as int. But when you call it - you never assigned a value to your ints that you put as parameter. So I doubt that the java code given will work:
    - No Test method available
    - you use 2 parameters that wasn't initialized (Or is the java compiler not warning on that? (I cannot tets anything on that because I never install software from untrusted companies and a company that adds crappy 3rd party software like webbrowser bars and anti virus software to a simple product that has nothing to do with it is not trustworthy at all.)

    So if you make code examples: Try to add all code required.

    With kind regards,

    Konrad

    Friday, February 8, 2013 5:29 AM
  • Hi,

    Thank you for your quick response and I found out something and tested seems like similar to my java code below.

    // in Java
    Class Test
    {
    public static Test Process(B b) throws MessageException
    {
      Class<?> mclass=null;
      Test newTest = null;
      int len;
      int data;
    
    
      Method mth = mclass.getDeclaredMethod("Process", B.class, int.class, int.class);
    
     newTest = (Test)mth.invoke(null, b, len, data);
     
    }
    }
    
    class B
    {
       // Do Something
      
    }

    Here Process is inside the same Test Class

    Equivalnet CSharp is

    Class Test
    { 
    // Create MyClass object
    MyClass myClassObj = new MyClass();
    
    // Get the Type information.
    Type myTypeObj = myClassObj.GetType();
    
    // Get Method Information.
    MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
    object[] mParam = new object[] {5, 10};
    
    // Get and display the Invoke method.
    Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " + myMethodInfo.Invoke(myClassObj, mParam) + "\n");
    }
    public class MyClass
    {
       public virtual int AddNumb(int numb1, int numb2)
       {
           int result = numb1 + numb2;
           return result;
       }
    
    }

    Here AddNumb is outside the Test Class and pls advise my code snippet is right or wrong as well my assumption.

    Thanks and best regards

    Friday, February 8, 2013 6:36 AM
  • Hi,

    all I can say is, that your C# example seems correct. If it is the equivalent to your java code? mclass in your java code is null and you call something on it - that seems strange for me - in C# that would already cause a null reference exception. (If it is a static method, then c# would enforce the call with the classname instead of a variable name!)

    But ow I understood that you want to call a static method in the same class?

    First of all I want to mention that reflection is quite nice but it cost a lot if you check the runtime results (same in java!). So you should avoid it whenever possible. So even if you load unknown components I would suggest to use Interfaces or superclasses to access the new classes. So as an example: We have a system that can execute Tasks. 3rd party developers can extend it with their own tasks. But we only use classes from the Reflection area to load the assemblies and go through the available classes to find all Tasks. Then we only use these classes as Tasks - so we do not use reflection to call methods.

    But let us come back to the example. You want to call a static method that is inside the class:

    http://blogs.microsoft.co.il/blogs/bursteg/archive/2006/11/15/InvokeStaticGenericMethod.aspx
    explains it quite nice. The core stuff is the same. You need the Type information and that could be grabbed through a call to typeof. (In your example typeof(Test))
    Then you get the method - it is more or less the same as before.
    In the blog the method had a generic inside. You do not have a generic so you do not have to do the next step that is done there. YOu can use the MethodInfo in the same way as you did in your current example.

    With kind regards,

    Konrad

    Friday, February 8, 2013 7:00 AM
  • Hi Konard,

    Thank you for your advice and the C# example is similar to Java code except methods implementation inside the classes only.

    Same is here in Java and C#

    // in Java

    Method mth = mclass.getDeclaredMethod("AddNumb", B.class, int.class, int.class);

    newTest
    = (Test)mth.invoke(null, b, len, data);
    // Create MyClass object MyClass myClassObj = new MyClass(); // Get the Type information. Type myTypeObj = myClassObj.GetType(); // Get Method Information. MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb"); object[] mParam = new object[] {5, 10}; // Get and display the Invoke method. Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " + myMethodInfo.Invoke(myClassObj, mParam) + "\n");

    Here is definition for getDeclareMethod and invoke in Java

    // Method Definition in Java
    getDeclaredMethod
    
    public Method getDeclaredMethod(String name,
                                    Class<?>... parameterTypes)
                             throws NoSuchMethodException,
                                    SecurityException
    invoke
    
    public Object invoke(Object obj,
                         Object... args)
                  throws IllegalAccessException,
                         IllegalArgumentException,
                         InvocationTargetException
    

    Pls advise whether my usage in C# is fine with Java as working code snippet.

    Best regards


    Wednesday, February 13, 2013 2:28 AM
  • Hi,

    Forgot to mention that the detailed Java Method below

    // in Java
    public abstract class Test
    {
       // Here TIS is public class
       public static Test Process(TIS tis) throws ErrorException
       {
            Test t= null;               
            Class<?> mclass=null;
    
            Method mth = mclass.getDeclaredMethod("Process", TIS.class, int.class, int.class);
           
            int len;
            int ver;  
    
            t = (Test) mth.invoke(null, tis, len, ver);
    
            return t;
         
       }
    }

    Pls advise me the same or correct implementation in C#.

    Thanks and best regards

    Wednesday, February 13, 2013 2:45 AM
  • You are doing it right. I checked your code. But Konard is absolutely right when he says use interface rather than reflection. You will face performance related issues in longer run.

    Class Test
    { 
    // Create MyClass object
    MyClass myClassObj = new MyClass();
    
    // Get the Type information.
    Type myTypeObj = myClassObj.GetType();
    
    // Get Method Information.
    MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
    object[] mParam = new object[] {5, 10};
    
    // Get and display the Invoke method.
    Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " + myMethodInfo.Invoke(myClassObj, mParam) + "\n");
    }


    Thanks, Durgesh Chaudhary. http://home.techphernalia.com

    Thursday, February 14, 2013 6:12 AM
  • Hi,

    Thank you for your prompt advice but the method used in GetMethod is inside the same class as shown in java.

    // in Java
    public abstract class Test
    {
       // Here TIS is public class
       public static Test Process(TIS tis) throws ErrorException
       {
            Test t= null;               
            Class<?> mclass=null;
    
            Method mth = mclass.getDeclaredMethod("Process", TIS.class, int.class, int.class);
           
            int len;
            int ver;  
    
            t = (Test) mth.invoke(null, tis, len, ver);
    
            return t;
         
       }
    }

    it could be affect the performance if used reflection for long run but the original java code is still there n time constraint.

    if interface, how is the best implementation pls let me know.

    Best regrads

    Thursday, February 14, 2013 6:27 AM
  • Hi,

    What I mean is process method used in mclass.getDeclaredMethod("Process", TIS.class, int.class, int.class);

    Here is also type cast with null object , t = (Test) mth.invoke(null, tis, len, ver);

    Best regards

    Thursday, February 14, 2013 6:29 AM
  • Good morning Durgesh and Konrad,

    Any good news for my assumption and since I start to test today onwards all methods.

    Thanks and best regards

    Monday, February 18, 2013 2:04 AM
  • Dear Mr Louis,

    I am looking for the concrete solution of Signed Unsigned Integer with Socket, Memory Stream and Stream using Visual Studio 2008 SP1.

    Here is my code snippet for memory stream and socket and wrong results as below.

    // CSharp for Memory Stream
    sbyte[] signed = { -128, -121, 0, 1, 127 };
    byte[] unsigned = (byte[])(Array)signed;
    sbyte[] tmpArr = (sbyte[])(Array)unsigned;
    byte[] retUnsigned = new byte[unsigned.Length];
    Stream memStr = new MemoryStream(unsigned, 0, unsigned.Length);
    memStr.Read(retUnsigned, 0, unsigned.Length);
    
    // result 
    retUnsigned = { 128, 135, 0, 1, 127 };

    // CSharp Socket Client Side
    socket m_sock;
    sbyte[] signed = { -128, -121, 0, 1, 127 };
    m_sock.Send((byte[])(Array)signed, signed.Length, 0);
    
    // CSharp Socket Server Side
    // IAsyncResult ar
    
    nBytesRec = m_sock.EndReceive(ar);
    byte [] byReturn = new byte[nBytesRec];
    Array.Copy( m_byBuff, byReturn, nBytesRec );
    string recData = System.Text.Encoding.ASCII.GetString(byReturn);
    Console.WriteLine("ReceivedData : {0}", recData);
    
    // result is same as memory stream
    byReturn = [128, 135, 0 , 121, 127]

    I hope you will advise me to get it in a right track.

    Thanks and best regards

    Wednesday, February 27, 2013 6:52 AM
  • 1) I don't see any link between your last post and the thread question.

    2) Why do you think you're getting wrong results? What you show is the correct interpretation of the input as unsigned bytes.

    Thursday, February 28, 2013 3:16 PM