what is the Class object (java.lang.Class)? -


the java documentation class says:

class objects constructed automatically java virtual machine classes loaded , calls defineclass method in class loader.

what these class objects? same objects instantiated class calling new?

also, example object.getclass().getname() how can typecasted superclass class, if don't inherit java.lang.class?

nothing gets typecasted class. every object in java belongs class. that's why object class, inherited other classes, defines getclass() method.

getclass(), or class-literal - foo.class return class object, contains metadata class:

  • name
  • package
  • methods
  • fields
  • constructors
  • annotations

and useful methods casting , various checks (isabstract(), isprimitive(), etc). the javadoc shows information can obtain class.

so, example, if method of yours given object, , want process in case annotated @processable annotation, then:

public void process(object obj) {     if (obj.getclass().isannotationpresent(processable.class)) {        // process somehow;      } } 

in example, obtain metadata class of given object (whatever is), , check if has given annotation. many of methods on class instance called "reflective operations", or "reflection. read here reflection, why , when used.

note enums , interfaces represent class object, , have respective metadata.

to summarize - each object in java has (belongs to) class, , has respective class object, contains metadata it, accessible @ runtime.


Comments