How to get a class name dynamically?

时间:2016-04-04 17:30:41

标签: java

I have a classA which contains following code snippet:

 public classA {

    public static Integer getValue(int x) {
      system.out.println(x);
      System.out.println(Qualifiedclassname that where you got the xvalue);
      return x;
    }
 }

The above class contains a method called getValue() which returns int as its declared as argument. This method would be called in another class files like below:

 public class B {

   @Parameters{value}
   public static void setValue(int value) {
     ClassA.getValue(value);
    }
 }

I just want to get a "class name" of the value where I'm getting it. As per above code Class B is giving a value for the getValue() method. I would like to print a class name of b in output console as "com.online.getvaluecode.ClassB".

As per my requirement, I can't use any of the below code in ClassB(client level code, but it can be used in Class A inside getValues()method):

    this.getClass().getName(); or  
    Class<?> enclosingClass = getClass().getEnclosingClass();
    enclosingClass.getName();

Class B always used to call ClassA.getValue(x) method, and It has to print the value as well "class name" where I'm getting int value for that method. I don't have permission to use any object creation in ClassB. All I have to do, call the ClassA.getValue(x);

3 个答案:

答案 0 :(得分:4)

The straight-forward way is to generate a stacktrace, parse it, and find the caller:

Exception ex = new Exception();
ex.fillInStackTrace();
StackTraceElement[] trace = ex.getStackTrace();
String caller = trace[1].getClassName(); // trace[0] is us, trace[1] is our caller

Though this is generally not very performant, and should not be used in regular operation. "Who called this method" is generally not relevant in the majority of situations, and due to runtime optimizations (inlining, among other things) this information may not even be available at all. Some JVMs do not provide stack trace information because it is very expensive to provide.

I would reconsider your approach and make sure you really need to know who called your method.

答案 1 :(得分:0)

in the method getValue(...) you get the int as parameter, the class that is calling that method is not relevant for that method per se, so java is not giving any way to get that info inside the method...

答案 2 :(得分:0)

One option is to create Exception object and call fillInStackTrace method and finally call getStackTrace() method. It returns StackTrace array from which you can get the caller of this method.