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?
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.
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.
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.
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;
You can just do this:
var callingClass = new StackFrame(1).GetMethod().ReflectedType;
The 1
tells the constructor to skip the currently executing method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With