Results 1 to 5 of 5
  1. #1
    NTech is offline Member
    Join Date
    Jun 2010
    Posts
    1
    Rep Power
    0

    Default getDeclaringClass()

    Hey guys, i am trying to find out how to find out which class a constructor is called from, and from there using that class to fill in a variable, instead of having to have a class parameter in my constructor.

    Ive Tried this:

    Java Code:
    public class s {
    	private Class<?> dClass;
    	
    	public s(){
    		dClass = this.getClass().getDeclaringClass();
    	}
    	
    	public Class<?> getDClass(){
    		return dClass;
    	}
    }
    
    
    public class test {
    
    	public static void main(String[] args){
    		s se = new s();
    		System.out.println(se.getDClass());
    	}
    
    }
    but the output is always null.

    This is what i am trying to avoid:

    Java Code:
    public class s {
    	private Class<?> dClass;
    	
    	public s(Class<?> dclass){ // this param would always be test.class
    		dClass = dclass;
    	}
    	
    	public Class<?> getDClass(){
    		return dClass;
    	}
    }
    Last edited by NTech; 06-14-2010 at 05:55 AM.

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    What do you need the calling class for? If this class is going to take different actions based on the subclass, then you are doing things wrong. The classes are too tightly coupled.

    You should, rather, be declaring abstract methods in the super class for the subclasses to implement.

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,611
    Rep Power
    25

    Default

    class parameter in my constructor
    That would be a better way.

  4. #4
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    I would second masijade's question - "What do you need the calling class for?"

    If you could explain what it is you want to achieve by this, we could probably provide alternatives.

  5. #5
    iluxa is offline Senior Member
    Join Date
    Mar 2010
    Posts
    266
    Rep Power
    5

    Default

    you aren't using getDeclaringClass correctly. read the APIs again.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •