Class.class and class.getClass, whats the difference

S

seyal.v.p

hi,

Is Class.class different from instanceOfClass.getClass() ?

I know it sounds blank. Let me explain the problem that I faced in
detail;
I have a class Class A with 2 protected methods and a private List
object.

Now in the test class of Class A, in a test case, I create a inner
class for Class A and override the two protected methods of Class A..
In addition I try to set up data in the List using relection.

i.e

testMtd(){

A a = new A(){

// Code for two overriden protected mtds here

};

Field f = A.class.getDeclaredField("NameOfTheListInClassA"); //This
works
Field f = a.getClass().getDeclaredField("NameOfTheListInClassA");
//This doesnt

}

Can anyone explain why?


Thanks in advance,
Seyal
 
R

Robert Klemme

hi,

Is Class.class different from instanceOfClass.getClass() ?

I know it sounds blank. Let me explain the problem that I faced in
detail;
I have a class Class A with 2 protected methods and a private List
object.

Now in the test class of Class A, in a test case, I create a inner
class for Class A and override the two protected methods of Class A..
In addition I try to set up data in the List using relection.

i.e

testMtd(){

A a = new A(){

// Code for two overriden protected mtds here

};

Field f = A.class.getDeclaredField("NameOfTheListInClassA"); //This
works
Field f = a.getClass().getDeclaredField("NameOfTheListInClassA");
//This doesnt

}

Can anyone explain why?

This is not cause by a difference between Class.class and
instanceOfClass.getClass(). It's caused by the fact that a.getClass()
!= A.class, i.e. a is not an instance of A but of an anonymous sub class
of A. Note the difference between getDeclaredField() and getField():

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getDeclaredField(java.lang.String)
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getField(java.lang.String)

Regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top