Code demonstration of Java reflection and polymorphism (parent class calling subclass)

Source: Internet
Author: User

Package Test0817;

Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;

Class base{
int A;

Base () {
A=1;
System.out.println ("Base Construct");
}
public void F () {
System.out.println ("Base");
}
}

Class Sub extends base{
int A;
int b;
Sub () {
a=2;
b=2;
System.out.println ("Sub Construct");
}

Sub (int i) {
A=i;
B=i;
System.out.println ("Sub construct.this has one param");
}
public void F () {
System.out.println ("Sub");
}
public void f (int m) {
System.out.println ("sub,the m =" +m);
}
}

public class Testfanshe {

public static void Main (string[] args) throws Instantiationexception, Illegalaccessexception, SecurityException {
Class<?> C;
try {
c = Class.forName ("Test0817.sub"); The full package name is required. Class name
Sub s = (sub) c.newinstance ();//instantiation
Get the constructor function
C.getconstructors ();
Get the method
method = C.getmethod ("f");
System.out.println ("The Method is" +method.tostring ());

class[] Paramerclass = new Class[1];
Paramerclass[0] = Int.class; This place is going to write int, which is consistent with the parameter type of the formal parameter, and the method cannot be found by writing an integer.
Method method1 = C.getmethod ("f", Paramerclass);
System.out.println ("The Method is" +method1.tostring ());
Method of invoking the S object through reflection
Method.invoke (s); Parameter-free

int a=10;
Method1.invoke (S, a); of a parameter
Method1.invoke (S, 20);

Instantiation, pointing to the parent class reference
Base B = (base) c.newinstance ();
Base bs = (Sub) c.newinstance ();
Sub sb = (Base) c.newinstance (); Error
S.F (); Output Sub
B.f (); Output Sub
B.F (10);//error, unable to invoke child class method not in parent class
BS.F (); Output Sub
BS.F (10);//error, unable to invoke child class method not in parent class
} catch (ClassNotFoundException e) {
System.out.println ("No such exception occurs");
E.printstacktrace ();
}catch (Nosuchmethodexception e) {
System.out.println ("No such method exception occurred");
E.printstacktrace ();
}catch (IllegalArgumentException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (InvocationTargetException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

}

}

Output Result:

Base Construct
Sub Construct
The method is public void Test0817.sub.f ()
The method is public void Test0817.sub.f (int)
Sub
Sub,the m = 10
Sub,the m = 20
Base Construct
Sub Construct
Base Construct
Sub Construct

 PackageTest0817;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;classbase{intA; Base () {a=1; System.out.println ("Base Construct"); }     Public voidf () {System.out.println ("Base"); }}classSubextendsbase{intA; intb; Sub () {a=2; b=2; System.out.println ("Sub Construct"); } Sub (inti) {a=i; b=i; System.out.println ("Sub Construct.this has one param"); }     Public voidf () {System.out.println ("Sub"); }     Public voidFintm) {System.out.println ("Sub,the m =" +m); }} Public classTestfanshe { Public Static voidMain (string[] args)throwsinstantiationexception, Illegalaccessexception, SecurityException {Class<?>C; Try{C= Class.forName ("Test0817.sub");//the full package name is required. class nameSub s = (sub) c.newinstance ();//instantiation of//get the constructor functionc.getconstructors (); //Get the methodmethod = C.getmethod ("F"); System.out.println ("The method is" +method.tostring ()); Class[] Paramerclass=NewClass[1]; paramerclass[0] =int.class;//This place is going to write int, which is consistent with the parameter type of the formal parameter, and the method cannot be found by writing an integer .Method method1 = C.getmethod ("F", Paramerclass); System.out.println ("The method is" +method1.tostring ()); //method of invoking the S object through reflectionMethod.invoke (s);//parameter-free                        inta=10; Method1.invoke (S, a); //of a parameterMethod1.invoke (S, 20); //instantiation, pointing to the parent class referenceBase B =(Base) c.newinstance (); Base BS=(Sub) c.newinstance (); //Sub sb = (Base) c.newinstance (); ErrorS.F ();//Output SubB.f ();//Output Sub//B.f (ten);//error, unable to call child class method not in parent classBS.F ();//Output Sub//BS.F (ten);//error, unable to call child class method not in parent class}Catch(ClassNotFoundException e) {System.out.println ("No such exception occurred");        E.printstacktrace (); }Catch(nosuchmethodexception e) {System.out.println ("No This method exception occurred");        E.printstacktrace (); }Catch(IllegalArgumentException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(InvocationTargetException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }}
View Code

Code demonstration of Java reflection and polymorphism (parent class calling subclass)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.