Java.class

In Java, given an object, an instance of a class, you can get the class name by coding the following:

Class clazz = obj.getClass();
String clazzName = clazz.getName();

Sometimes you want you want to create a Class object for a given class. In this case you can do so by writing code similar to the following example:

Class clazz = MyClass.class;

Many plugin frameworks, including the JDBC Driver Manager will create a Class object without having the knowledge of what class name at compile time. There might be a case where you know a class implements a given interface but you don’t know the class name of the implementation until at runtime when you read it from a properties file. In situations like this you can do the following:

String clazzName = "com.juixe.techknow.MyClass";
...
Class clazz = Class.forName(clazzName);

Sometimes you will need a Class object for a primitive type. You might need a Class object for an int or boolean when dealing with reflection. In this case you do so using the dot class notation on a primitive type. Here is a more elaborate example where we create a Class object for an int primitive:

int newValue = ...
Class clazz = obj.getClass();
Method meth = clazz.getMethod("setValue", new Class[]{int.class});
meth.invoke(obj, new Object[]{new Integer(newValue)});

You can also get the class for an array. The only place where I have ever need the class of an array is when working with reflection. Here is how you can get the class for an array:

Class clazz = String[].class;

Technorati Tags: , , ,

Related posts:

  1. Java Nested Inner Class This
  2. Fix Common Java Exceptions
  3. Class HighLite GraphicsEnvironment
  4. Embedding Groovy
  5. Jakarta BeanUtils PropertyUtils

This entry was posted in Java, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*