The Artima Developer Community
Sponsored Link

Java Answers Forum
How to get Class within a static method

5 replies on 1 page. Most recent reply: Apr 9, 2006 6:50 PM by Kishori Sharan

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 5 replies on 1 page
Makhmud Kasumov

Posts: 16
Nickname: marik
Registered: Oct, 2005

How to get Class within a static method Posted: Apr 6, 2006 6:52 AM
Reply to this message Reply
Advertisement
Hello all!

Is there a way within a static method to get a Class object for the class to which this very static method belongs?

Thanks


Makhmud Kasumov

Posts: 16
Nickname: marik
Registered: Oct, 2005

Re: How to get Class within a static method Posted: Apr 6, 2006 6:53 AM
Reply to this message Reply
Yeah, little correction: a way without using the class name directly, of course.

Dave Hinton

Posts: 42
Nickname: catbells
Registered: Oct, 2003

Re: How to get Class within a static method Posted: Apr 6, 2006 12:51 PM
Reply to this message Reply
No.

Kishori Sharan

Posts: 211
Nickname: kishori
Registered: Feb, 2002

Re: How to get Class within a static method Posted: Apr 6, 2006 7:34 PM
Reply to this message Reply
public class Test {
	public static void main(String[] args) {
		try{
			throw new Exception();
		}
		catch(Exception e){
			StackTraceElement[] sTrace = e.getStackTrace();
			// sTrace[0] will be always there
			String className = sTrace[0].getClassName();
			System.out.println(className);
 
		}
	}
 
}

Makhmud Kasumov

Posts: 16
Nickname: marik
Registered: Oct, 2005

Re: How to get Class within a static method Posted: Apr 6, 2006 11:52 PM
Reply to this message Reply
Thanks, that's it!
I guess there's even no need to throw the exception. You can simply create it and access StackTraceElement array right away.

Kishori Sharan

Posts: 211
Nickname: kishori
Registered: Feb, 2002

Re: How to get Class within a static method Posted: Apr 9, 2006 6:50 PM
Reply to this message Reply
You are right that you don't need to throw exception to get its stack trace. I looked the source code for Throwable class and it fills in the stack trace in its constructor. That is, as soon as an object of Throwable class is created it knows where in source code it is being created, which is enough to get the class name.

Thanks
Kishori

Flat View: This topic has 5 replies on 1 page
Topic: boolean Previous Topic   Next Topic Topic: Error in Tomcat

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use