Java Study Notes-11. type identification during runtime, Study Notes-11
1. The getClasses () method of the Class Object obtains all public internal classes in the Class and internal classes inherited from the parent Class and parent interface. The getinterfaces () method returns all interfaces inherited by the class.
Import javax. print. attribute. standard. printerInfo; interface HasBatteries {} interface Waterproof {} interface ShootsThings {} class Toy {Toy () {} Toy (int I) {}} class FancyToy extends Toy implements HasBatteries, Waterproof, shootsThings {public FancyToy () {// TODO automatically generated constructor stub super (1) ;}} public class ToyTest {public static void main (String [] args) {Class class1 = null; try {class1 = class1.forName ("FancyToy ");} Catch (ClassNotFoundException e) {// TODO: handle exception} printInfo (class1); Class [] faces = class1.getInterfaces (); for (int I = 0; I <faces. length; I ++) {printInfo (faces [I]);} Class cy = class1.getSuperclass (); Object cObject = null; try {cObject = cy. newInstance ();} catch (Exception e) {// TODO: handle exception} printInfo (cObject. getClass ();} static void printInfo (Class cc) {System. out. println (" Class name: "+ cc. getName () +" is interface? "+ Cc. isInterface ());}}
2. When using the forName () of the Class object, the Class name classname parameter must be the full name. You cannot add only the Class name, such as the package name, Class name, and java. lang. String.
Package eleven; import java. lang. reflect. *; class Pig {public Pig () {// The constructor stub automatically generated by TODO} public void T () {} public void A () {} public void ma () {}} public class ShowMethods {public static void main (String [] args) {try {// Class class1 = Class. forName ("eleven. pig "); Class class1 = Class. forName ("java. lang. string "); Method [] methods = class1.getMethods (); Constructor [] constructors = class1.getConstructors (); for (int I = 0; I <methods. length; I ++) {System. out. println (methods [I]. toString () ;}for (int I = 0; I <constructors. length; I ++) {System. out. println (constructors [I]. toString () ;}} catch (ClassNotFoundException e) {// TODO: handle exception System. out. println ("No such class:" + e );}}}