Java.lang.Class.asSubclass() Method



Description

The java.lang.Class.asSubclass() method casts this Class object to represent a subclass of the class represented by the specified class object.It is useful when a client needs to "narrow" the type of a Class object to pass it to an API that restricts the Class objects that it is willing to accept.

Declaration

Following is the declaration for java.lang.Class.asSubclass() method

public <U> Class<? extends U> asSubclass(Class<U> clazz)

Parameters

NA

Return Value

This method returns this Class object, cast to represent a subclass of the specified class object.

Exception

ClassCastException − if this Class object does not represent a subclass of the specified class (in this "subclass" includes the class itself).

Example

The following example shows the usage of java.lang.Class.asSubclass() method.

package com.tutorialspoint;

import java.lang.*;

public class ClassDemo {

   public static void main(String[] args) {

     try {
         ClassDemo cls = new ClassDemo();
         ClassDemo subcls = new SubClass1(); 

         // class ClassDemo
         Class c = cls.getClass(); 
         System.out.println(c);

         // sub class SubClass1
         Class c1 = subcls.getClass();
         System.out.println(c1);

         // represent a subclass of the specified class object
         Class retval = c1.asSubclass(c);

         System.out.println(retval);
      } catch(ClassCastException e) {
         System.out.println(e.toString());
      }
   }
}

class SubClass1 extends ClassDemo {
   // sub class
} 

Let us compile and run the above program, this will produce the following result −

class com.tutorialspoint.ClassDemo
class com.tutorialspoint.SubClass1
class com.tutorialspoint.SubClass1
java_lang_class.htm
Advertisements