Check if a Class Object is subclass of another Class Object in Java

前端 未结 8 1012
鱼传尺愫
鱼传尺愫 2020-11-28 20:33

I\'m playing around with Java\'s reflection API and trying to handle some fields. Now I\'m stuck with identifying the type of my fields. Strings are easy, just do myFi

8条回答
  •  北海茫月
    2020-11-28 21:06

    instanceof works on instances, i.e. on Objects. Sometimes you want to work directly with classes. In this case you can use the asSubClass method of the Class class. Some examples:

    1)

        Class o=Object.class;
        Class c=Class.forName("javax.swing.JFrame").asSubclass(o);
    

    this will go through smoothly because JFrame is subclass of Object. c will contain a Class object representing the JFrame class.

    2)

        Class o=JButton.class;
        Class c=Class.forName("javax.swing.JFrame").asSubclass(o);
    

    this will launch a java.lang.ClassCastException because JFrame is NOT subclass of JButton. c will not be initialized.

    3)

        Class o=Serializable.class;
        Class c=Class.forName("javax.swing.JFrame").asSubclass(o);
    

    this will go through smoothly because JFrame implements the java.io.Serializable interface. c will contain a Class object representing the JFrame class.

    Of course the needed imports have to be included.

提交回复
热议问题