Reflection and Getdeclaredmethods () and getmethods () differences

Source: Internet
Author: User

Content reproduced from http://blog.csdn.net/ljphhj/article/details/12858767

Package Cn.lee.demo;

Import Java.lang.reflect.Constructor;
Import Java.lang.reflect.Field;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Modifier;
Import java.lang.reflect.TypeVariable;

public class Main {
/**
* In order to see the Java reflection part of the code, all exceptions I finally throw to the virtual machine processing!
* @param args
* @throws ClassNotFoundException
* @throws instantiationexception
* @throws illegalaccessexception
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws nosuchfieldexception
* @throws SecurityException
* @throws nosuchmethodexception
*/
public static void Main (string[] args) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, InvocationTargetException, SecurityException, Nosuchfieldexception, nosuchmethodexception {
TODO auto-generated Method Stub

Demo1. Get the package name and class name of the class through the Java reflection mechanism
Demo1 ();
System.out.println ("===============================================");

Demo2. Verify that all classes are instance objects of class
Demo2 ();
System.out.println ("===============================================");

Demo3. Using the Java reflection mechanism to create class objects with class [This is where the meaning of reflection exists], without a parameter construct
Demo3 ();
System.out.println ("===============================================");

Demo4: The constructor of a class is obtained through the Java reflection mechanism, and the construction of the parameter instance object is implemented.
Demo4 ();
System.out.println ("===============================================");

DEMO5: Manipulating member variables through the Java reflection mechanism, set and get
Demo5 ();
System.out.println ("===============================================");

Demo6: Some properties of the class are obtained through the Java reflection mechanism: inherited interfaces, parent classes, function information, member information, types, etc.
Demo6 ();
System.out.println ("===============================================");

Demo7: Calling methods in a class through the Java reflection mechanism
Demo7 ();
System.out.println ("===============================================");

Demo8: Obtaining the class loader through the Java reflection mechanism
Demo8 ();
System.out.println ("===============================================");

}

/**
* Demo1: Gets the package name and class name of the class through the Java reflection mechanism
*/
public static void Demo1 ()
{
person person = new person ();
System.out.println ("Demo1: Package Name:" + Person.getclass (). Getpackage (). GetName () + ","
+ "Full class Name:" + Person.getclass (). GetName ());
}

/**
* Demo2: Verify that all classes are instance objects of class
* @throws ClassNotFoundException
*/
public static void Demo2 () throws ClassNotFoundException
{
Define two classes with unknown types, set the initial value to null, and see how to assign them to a person class
class<?> Class1 = null;
Class<?> class2 = null;

Notation 1, may throw classnotfoundexception [multi-use this notation]
Class1 = Class.forName ("Cn.lee.demo.Person");
System.out.println ("Demo2: (notation 1) package name:" + class1.getpackage (). GetName () + ","
+ "Full class Name:" + class1.getname ());

Notation 2
Class2 = Person.class;
System.out.println ("Demo2: (notation 2) package name:" + class2.getpackage (). GetName () + ","
+ "Full class Name:" + class2.getname ());
}

/**
* DEMO3: Using the Java reflection mechanism to create class objects with class [This is where the meaning of reflection exists]
* @throws ClassNotFoundException
* @throws illegalaccessexception
* @throws instantiationexception
*/
public static void Demo3 () throws ClassNotFoundException, Instantiationexception, illegalaccessexception
{
class<?> Class1 = null;
Class1 = Class.forName ("Cn.lee.demo.Person");
Because there is no parameter, so you want to instantiate this class person, must have a parameterless constructor ha ~
Person person = (person) class1.newinstance ();
Person.setage (20);
Person.setname ("Leefeng");
System.out.println ("Demo3:" + person.getname () + ":" + person.getage ());
}

/**
* Demo4: The constructor of a class is obtained through the Java reflection mechanism, and the implementation of the parameter instance object is created.
* @throws ClassNotFoundException
* @throws InvocationTargetException
* @throws illegalaccessexception
* @throws instantiationexception
* @throws IllegalArgumentException
*/
public static void Demo4 () throws ClassNotFoundException, IllegalArgumentException, Instantiationexception, Illegalaccessexception, InvocationTargetException
{
class<?> Class1 = null;
person person1 = null;
person person2 = null;

Class1 = Class.forName ("Cn.lee.demo.Person");
Get a set of constructor functions
Constructor<?>[] Constructors = class1.getconstructors ();

Person1 = (person) constructors[0].newinstance ();
Person1.setage (30);
Person1.setname ("Leefeng");

Person2 = (person) constructors[1].newinstance ("Leefeng");

System.out.println ("Demo4:" + person1.getname () + ":" + person1.getage ()
+ "," + person2.getname () + ":" + person2.getage ()
);

}

/**
* DEMO5: Manipulate member variables through the Java reflection mechanism, set and get
*
* @throws illegalaccessexception
* @throws IllegalArgumentException
* @throws nosuchfieldexception
* @throws SecurityException
* @throws instantiationexception
* @throws ClassNotFoundException
*/
public static void Demo5 () throws IllegalArgumentException, Illegalaccessexception, SecurityException, Nosuchfieldexception, Instantiationexception, classnotfoundexception
{
class<?> Class1 = null;
Class1 = Class.forName ("Cn.lee.demo.Person");
Object obj = class1.newinstance ();

Field Personnamefield = Class1.getdeclaredfield ("name");
Personnamefield.setaccessible (TRUE);
Personnamefield.set (obj, "Fat Tiger first Sen");


System.out.println ("Demo5: Gets the value of the property variable after modifying the property:" + personnamefield.get (obj));

}

/**
* Demo6: Some properties of the class are obtained through the Java reflection mechanism: inherited interfaces, parent classes, function information, member information, types, etc.
* @throws ClassNotFoundException
*/
public static void Demo6 () throws ClassNotFoundException
{
class<?> Class1 = null;
Class1 = Class.forName ("Cn.lee.demo.SuperMan");

Get Parent class Name
Class<?> superclass = Class1.getsuperclass ();
System.out.println ("Parent class name of the Demo6:superman class:" + Superclass.getname ());

System.out.println ("===============================================");


field[] fields = Class1.getdeclaredfields ();
for (int i = 0; i < fields.length; i++) {
System.out.println ("Member in class:" + Fields[i]);
}
System.out.println ("===============================================");


Get class method
Method[] methods = Class1.getdeclaredmethods ();
for (int i = 0; i < methods.length; i++) {
System.out.println ("Demo6, obtain Superman class method:");
System.out.println ("Function name:" + methods[i].getname ());
System.out.println ("function return type:" + methods[i].getreturntype ());
System.out.println ("function access modifier:" + modifier.tostring (Methods[i].getmodifiers ()));
System.out.println ("Function code notation:" + methods[i]);
}

System.out.println ("===============================================");

Get the interface of the class implementation, because the interface class also belongs to class, so get the method in the interface is the same way to get ha
class<?> interfaces[] = class1.getinterfaces ();
for (int i = 0; i < interfaces.length; i++) {
SYSTEM.OUT.PRINTLN ("Implemented interface class name:" + interfaces[i].getname ());
}

}

/**
* Demo7: Calling class methods through the Java reflection mechanism
* @throws ClassNotFoundException
* @throws nosuchmethodexception
* @throws SecurityException
* @throws InvocationTargetException
* @throws illegalaccessexception
* @throws IllegalArgumentException
* @throws instantiationexception
*/
public static void Demo7 () throws ClassNotFoundException, SecurityException, Nosuchmethodexception, IllegalArgumentException, Illegalaccessexception, InvocationTargetException, instantiationexception
{
class<?> Class1 = null;
Class1 = Class.forName ("Cn.lee.demo.SuperMan");

System.out.println ("Demo7: \ n calls the No parameter Method fly ():");
method = Class1.getmethod ("Fly");
Method.invoke (Class1.newinstance ());

SYSTEM.OUT.PRINTLN ("Call the parameter method walk (int m):");
method = Class1.getmethod ("Walk", Int.class);
Method.invoke (Class1.newinstance (), 100);
}

/**
* Demo8: Class loader information is obtained through the Java reflection mechanism
*
* There are three kinds of class loaders in Java. [This piece of information on-line interception]

1) Bootstrap ClassLoader This loader is written in C + + and is rare in general development.

2) Extension ClassLoader is used to load extended classes, generally corresponding to classes in the Jre\lib\ext directory

3) Appclassloader load Classpath The specified class, which is the most commonly used loader. It is also the default loader in Java.
*
* @throws ClassNotFoundException
*/
public static void Demo8 () throws ClassNotFoundException
{
class<?> Class1 = null;
Class1 = Class.forName ("Cn.lee.demo.SuperMan");
String namestring = Class1.getclassloader (). GetClass (). GetName ();

System.out.println ("Demo8: Class loader class Name:" + namestring);
}



}
/**
*
* @author Xiaoyaomeng
*
*/
Class person{
private int age;
private String name;
Public person () {

}
public person (int age, String name) {
This.age = age;
THIS.name = name;
}

public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
}

Class Superman extends person implements Actioninterface
{
Private Boolean bluebriefs;

public void Fly ()
{
System.out.println ("Superman will fly Yes ~ ~");
}

public Boolean isbluebriefs () {
return bluebriefs;
}
public void Setbluebriefs (Boolean bluebriefs) {
Bluebriefs = Bluebriefs;
}

@Override
public void Walk (int m) {
TODO auto-generated Method Stub
System.out.println ("Superman will walk Yes ~ ~ Go" + M + "meters will not move! ");
}
}
Interface actioninterface{
public void Walk (int m);
}

Getdeclaredmethods () and getmethods () differences

getDeclaredMethods()
Returns Method an array of objects that reflect Class all the methods that this object represents for the class or interface declaration, including public, protected, default (package) access, and private methods, but not inherited methods.

getMethods()
Returns an array containing some Method objects that reflect the Class public member of the class or interface represented by this object, including those declared by the class or interface, and those inherited from the superclass and the hyper-interface method.

Reflection and Getdeclaredmethods () and getmethods () differences

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.