google reflections - Java - determine where an object is instantiated from object's class -
say have class called myclass
, within class, want find out class name instantiated object of myclass
, example:
class myclass { final string whocreatedme; public myclass() { whocreatedme = ??? } } public class driver { public static void main(string[] args) { system.out.println(new myclass().whocreatedme); // should print driver } }
this not advisable, , breaks in unexpected (and expected) ways. hope you're not going use in production code.
public class temp { static class testclass { public final string whocreatedme; public testclass() { stacktraceelement ste = thread.getallstacktraces().get(thread.currentthread())[3]; whocreatedme = ste.getclassname(); } } public static void main(string[] args) throws exception { system.out.println(new testclass().whocreatedme); } }
Comments
Post a Comment