I'm attempting to create a better logging situation for myself. Currently I'm just custom writing a string and logging that string. What I'd like to do instead is know the exact Class#method combination that I'm logging. Currently I'm writing it out such as:  Logger.push(String s) where s is something like "ClassA#myMethod: Successfully implemented database  What I want to do it make it a little easier on myself, my reducing the text I have to write if possible. I don't want to have to type ClassA#myMethod, instead what I want to do is pass a method and use reflection to get the desired names. Here's the example logger function I've created:  public static void push(String msg, Method cont){     logger.info(cont.getDeclaringClass().getSimpleName() + "#" + cont.getName() + ": " + msg); }   My issue is with passing the method. Ideally I'm looking for something like this, but for the actual method. Currently the only way I could think of is something like:  Logger.push("Hello World", getClass().getDeclaredMethods("thisMethodName");   I was just wondering if there was an easier to get the currently used function. Thanks!
2745
I need to find the caller of a method. Is it possible using stacktrace or reflection?
23661
Context Around this Code: I am making a schedulable class run each Sunday to track a couple of metrics important to the team.   Question: I am looking to consolidate DML operations and a big part of this is understanding pass by reference vs pass by value.  I want to pass the salesOps user object to the method SDREfficiencyLastWeek. I made the return type void, because I figured that I will be passing this by reference and I can make all the updates in the method without having to anything.   Why I am confused:    I read the above article and am thrown off by the following statement:  "Non-primitive data type arguments, such as sObjects, are also passed into methods by value. "   If the object is indeed passed by reference, then the query for the salesOps user in my code should be sufficient enough to edit all fields on that object without actually having to state each field in the query.  global class SDREfficientMetricsSchedulable implements Schedulable  {     global void execute(SchedulableContext sc)      {         User salesOps = [SELECT ID FROM USER WHERE id = '0056A000002Z3p9QAC'];         List&lt;String&gt; queries = new List&lt;String&gt;();          String contactsWorked_lastWeek  = 'select count(id) results from contact where LastActivityDate = last_week';         queries.add(contactsWorked_lastWeek);          String demosSet_lastWeek            = 'select count(id) results from form__c where CreatedDate = last_week';         queries.add(demosSet_lastWeek);          String demosCompleted_lastWeek  = 'select count(id) results from opportunity where (stagename = \'Unqualified Demo Completed\'  OR stagename = \'Qualified Demo Completed\' )  and RecordTypeId = \'0126A000000yudDQAQ\' and CloseDate = last_week';         queries.add(demosCompleted_lastWeek);          String qualifiedDemos_lastWeek  = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and isclosed = false and  SDR_Owner__c != null and CreatedDate = last_week';         queries.add(qualifiedDemos_lastWeek);          String closedWon_lastWeek       = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and iswon = true and  SDR_Owner__c != null and CloseDate = last_week';         queries.add(qualifiedDemos_lastWeek);            SDREfficiencyLastWeek(queries, salesOps);          update salesOps;     }       public void SDREfficiencyLastWeek(List&lt;String&gt; queries, User salesOps )     {        }  }
118537
In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a params so that the method parameter looks like an array but allows everyone using the method to pass as many parameters of that type as the caller wants.  I'm fairly sure Java supports similar behaviour, but I cant find out how to do it.
70153
In the code below I tried in two ways to access the parent version of methodTwo, but the result was always 2. Is there any way to get the 1 result from a ChildClass instance without modifying these two classes?  class ParentClass {     public int methodOne()     {         return methodTwo();     }      virtual public int methodTwo()     {         return 1;     } }  class ChildClass : ParentClass {     override public int methodTwo()     {         return 2;     } }  class Program {     static void Main(string[] args)     {         var a = new ChildClass();         Console.WriteLine("a.methodOne(): " + a.methodOne());         Console.WriteLine("a.methodTwo(): " + a.methodTwo());         Console.WriteLine("((ParentClass)a).methodTwo(): "          + ((ParentClass)a).methodTwo());         Console.ReadLine();     } }   Update ChrisW posted this:     From outside the class, I don't know   any easy way; but, perhaps, I don't   know what happens if you try   reflection: use the Type.GetMethod   method to find the MethodInfo   associated with the method in the   ParentClass, and then call   MethodInfo.Invoke   That answer was deleted. I'm wondering if that hack could work, just for curiosity.
21166
I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as Console.  For example, if I want to add an extension to Console, called 'WriteBlueLine', so that I can go:  Console.WriteBlueLine("This text is blue");   I tried this by adding a local, public static method, with Console as a 'this' parameter... but no dice!      public static class Helpers {     public static void WriteBlueLine(this Console c, string text)     {         Console.ForegroundColor = ConsoleColor.Blue;         Console.WriteLine(text);         Console.ResetColor();     } }   This didn't add a 'WriteBlueLine' method to Console... am I doing it wrong? Or asking for the impossible?
24638
I read  and thought that would easily be solved (not that it isn't solvable without) if one could write:   @Override public String toString() {     return super.super.toString(); }   I'm not sure if it is useful in many cases, but I wonder why it isn't and if something like this exists in other languages.  What do you guys think?  EDIT: To clarify: yes I know, that's impossible in Java and I don't really miss it. This is nothing I expected to work and was surprised getting a compiler error. I just had the idea and like to discuss it.
92031
Whats this syntax useful for :       function(String... args)   Is this same as writing       function(String[] args)    with difference only while invoking this method or is there any other feature involved with it ?
116879
Can someone explain to me why  @Override public void fooMethod(Class&lt;?&gt; c)   doesn't override  public void fooMethod(Class c)   and gives me the following errors instead:   - Name clash: The method fooMethod(Class&lt;?&gt;)  of type SubClass has the same erasure as fooMethod(Class) of  type SuperClass but  does not override it   - The method fooMethod(Class&lt;?&gt;) of type  SubClass must override a superclass method   ?  Edit: "java -version" says  Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284). As for the code snippet, it's already above, pretty much; the above extends the one below.
37164
Is there a way to get the name of the currently executing method in Java?
11352
Duplicate:     Maybe this is a very silly question but I don't understand why I can't declare two methods that have the same signature when they have different return types.  public class MyClass {     private double d = 0;      public double MyMethod()     {         return d;     }      public string MyMethod()     {         return d.ToString();     } }   I get a compile error that states that the class already defines a member with the same parameter types.  (Obviously the way I'm using this in my code isn't as simple as my example code...but I think it gets the idea across.)  Am I missing something concerning OO design that makes what I'm trying to do an OOP anti-pattern? Surely the compiler should be able to determine which method I'm trying to use as long as I specifically tell it which one I want.  Given MyClass myClass = new MyClass(); I would expect the following code to work:  double d = myClass.MyMethod(); string s = myClass.MyMethod();   I would expect the following code to have problems:  var v = myClass.MyMethod();   But even in the case of var it should result in a compile error.  Can anyone see what I'm doing wrong here? I'm more than happy to be corrected. :-)
123439
Ok, bear with me guys and girls as I'm learning.  Here's my question.  I can't figure out why I can't override a method from a parent class.  Here's the code from the base class (yes, I pilfered the java code from an OOP book and am trying to rewrite it in C#).  using System;  public class MoodyObject {     protected String getMood()     {         return "moody";     }      public void queryMood()     {         Console.WriteLine("I feel " + getMood() + " today!");     } }   and here are my other 2 objects that inherit the base class (MoodyObject):  using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace ConsoleApplication1 {     public class SadObject: MoodyObject     {         protected String getMood()         {             return "sad";         }          //specialization         public void cry()         {             Console.WriteLine("wah...boohoo");         }     } }   And:  using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace ConsoleApplication1 {     public class HappyObject: MoodyObject     {         protected String getMood()         {             return "happy";         }          public void laugh()         {             Console.WriteLine("hehehehehehe.");         }     } }   and here is my main:  using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {             MoodyObject moodyObject = new MoodyObject();             SadObject sadObject = new SadObject();             HappyObject happyObject = new HappyObject();              Console.WriteLine("How does the moody object feel today?");             moodyObject.queryMood();             Console.WriteLine("");             Console.WriteLine("How does the sad object feel today?");             sadObject.queryMood();             sadObject.cry();             Console.WriteLine("");             Console.WriteLine("How does the happy object feel today?");             happyObject.queryMood();             happyObject.laugh();         }     } }   As you can see, pretty basic stuff, but here's the output:     How does the moody object feel today?   I feel moody today!      How does the sad object feel today? I   feel moody today! wah...boohoo      How does the happy object feel today?   I feel moody today! hehehehehehe.   Press any key to continue . . .   Not as I expected.  I've tried to make the base method virtual and calling override when trying to override it and that just gets me this error "cannot override inherited member 'MoodyObject.getMood()' because it is not marked virtual, abstract, or override".  I also tried it without the virtual and override and it thinks I'm trying to hide the base method.  Again, I'm new to OOP and would appreciate any guidance.  EDITED TO ADD:  I found it!  The MoodyObject.cs was only a "solution item" in the solution explorer as opposed to a "ConsoleApplication1" item.  I dragged it down to where it belonged in the solution explorer and voila!  It works now.  I marked Luc's answer below as the answer because he offered the help I needed to get to where I have it resolved... I'm learning so much here.  It's amazing and you guys and girls are crazy smart!
30627
In C# the Main class has string[] args parameter.  What is that for and where does it get used?
96692
What method do I call to get the name of a class?
15435
I fear this is probably a bit of a dummy question, but it has me pretty stumped.  I'm looking for the simplest way possible to pass a method of an object into a procedure, so that the procedure can call the object's method (e.g. after a timeout, or maybe in a different thread).  So basically I want to:   Capture a reference to an object's method. Pass that reference to a procedure. Using that reference, call the object's method from the procedure.   I figure I could achieve the same effect using interfaces, but I thought there was another way, since this "procedure of object" type declaration exists.  The following doesn't work, but might it help explain where I'm confused...?  interface    TCallbackMethod = procedure of object;    TCallbackObject = class     procedure CallbackMethodImpl;     procedure SetupCallback;   end;  implementation  procedure CallbackTheCallback(const callbackMethod: TCallbackMethod); begin   callbackMethod(); end;  procedure TCallbackObject.CallbackMethodImpl; begin   // Do whatever. end;  procedure TCallbackObject.SetupCallback; begin   // following line doesn't compile - it fails with "E2036 Variable required"   CallbackTheCallback(@self.CallbackMethodImpl); end;   (Once the question is answered I'll remove the above code unless it aids the explanation somehow.)
1947
What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?  Consider the following sample code - inside the Example() method, what's the most concise way to invoke GenericMethod&lt;T&gt;() using the Type stored in the myType variable?  public class Sample {     public void Example(string typeName)     {         Type myType = FindType(typeName);          // What goes here to call GenericMethod&lt;T&gt;()?         GenericMethod&lt;myType&gt;(); // This doesn't work          // What changes to call StaticMethod&lt;T&gt;()?         Sample.StaticMethod&lt;myType&gt;(); // This also doesn't work     }      public void GenericMethod&lt;T&gt;()     {         // ...     }      public static void StaticMethod&lt;T&gt;()     {         //...     } }
25499
I think I might be missing the point of having a logging framework for your application.  In all the small apps I've always written a small "Logging" class and just pass log messages to a method in it which is written to a file.    What is the purpose of a 3rd party logging framework like log4net?  Is it thread safety with logging write operations or am I missing something?
67471
Consider the following code:  void Handler(object o, EventArgs e) {    // I swear o is a string    string s = (string)o; // 1    //-OR-    string s = o as string; // 2    // -OR-    string s = o.ToString(); // 3 }   What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?