Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine what class called a method?

I have an application in mind, but I am not sure how to do this. Say I have some publically accessible method in a DLL file that takes no parameters. Is it possible for this method to know what called it? Can it tell if it were called from a static or instantiated context? From a specific class? What can a method know about how it's being called?

like image 881
Corey Ogburn Avatar asked Nov 06 '12 15:11

Corey Ogburn


People also ask

How do you find the class method called?

var_dump(getClass($this)); Used in a method in namespace B this will give you the class that called a method in namespace B from namespace A.

Can we call method with class name?

We can have a method name same as a class name in Java but it is not a good practice to do so. This concept can be clear through example rather than explanations. In the below example, a default constructor is called when an object is created and a method with the same name is called using obj.

How do you define a method in class?

Like a class, a method definition has two major parts: the method declaration and the method body. The method declaration defines all the method's attributes, such as access level, return type, name, and arguments, as shown in the following figure. The method body is where all the action takes place.


2 Answers

You can get caller information from a stack trace:

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();

It is possible for this method to know what called it:

string typeName = methodBase.DeclaringType.Name;
string methodName = methodBase.Name;

It can tell if it were called from a static or instantiated context:

bool isStaticCall = methodBase.IsStatic

From a specific class:

bool isGeneric = methodBase.DeclaringType.IsGenericType;
like image 158
Sergey Berezovskiy Avatar answered Oct 01 '22 08:10

Sergey Berezovskiy


You can just do this:

var callingClass = new StackFrame(1).GetMethod().ReflectedType;

The 1 tells the constructor to skip the currently executing method.

like image 28
jgauffin Avatar answered Oct 01 '22 09:10

jgauffin