Suppose you have the following classes:
Package com.test.reflect;
public class Person
{
private int age;
private String name;
Public Persion ()
{
}
Public persion (String name)
{
THIS.name = name;
}
Public Persion (String name,int Age)
{
This (name);
This.age = age;
}
public void SetName (String name)
{
THIS.name = name;
}
public void Setage (int.)
{
This.age = age;
}
@hide
public void SetAll (String name,int Age)
{
SetName (name);
Setage (age);
}
private int Getage ()
{
return age;
}
Public String GetName ()
{
return name;
}
}
Because Getage () and SetAll () are private methods and @hide annotations, normal objects cannot be called. In order to be able to use these two methods, it can be reflected by:
public class Reflectdemo
{
public static void Main (string[] args) throws Exception
{
Get class Reference
Class class = Class.forName ("com.test.reflect.Persion");
Instantiating a Person object
Persion persion = (persion) class.newinstance ();//persion parameterless constructor
Persion persion = (persion) class.newinstance ("Xiaoming", 20);
Get SetAll function
Method setAll = Class.getmethod ("SetAll", String.class,int.class);
Call the SetAll function
Setall.invoke (persion, "Xiaohong", 18);
Get Getage function
Method getage = Class.getmethod ("Getage");
Call the Getage function
int age = (int) getage.invoke (persion);
System.out.println ("Name:" +persion.getname () + "Age:" +age);
}
}
This article is from the "whatever957" blog, make sure to keep this source http://whatever957.blog.51cto.com/6835003/1794404
Simple example of Java reflection