package aaa;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
Class clazz=Rectangle.class; //1
Class clazz1=Class.forName("aaa.Rectangle");//2
Rectangle r=new Rectangle();
Class clazz2=r.getClass(); //3
System.out.println(clazz==clazz1);
System.out.println(clazz1==clazz2);
/*Field[] fields = clazz.getDeclaredFields();
for(Field field:fields)
{
System.out.println(field.getName());
if("w".equals(field.getName()))
{
field.setAccessible(true);
field.set(r2, 100);
System.out.println(field.get(r2));
}
}*/
Constructor c=clazz.getConstructor(int.class,int.class);
Rectangle r3=(Rectangle)c.newInstance(1,2);
System.out.println(r3.length()+"=="+r3.area());
Constructor[] constructors = clazz.getConstructors();
for(Constructor c1:constructors)
{
System.out.println(c1.getName());
Class[] types = c1.getParameterTypes();
for(Class typeClass:types)
{
System.out.print(typeClass+" ");
}
System.out.println();
}
Method[] methods = clazz.getDeclaredMethods();
for(Method m:methods)
{
System.out.println(m.getName());
}
Rectangle r4=new Rectangle();
r4.setH(20);
r4.setW(40);
int length=r4.length();
int area=r4.area();
Rectangle r2=(Rectangle)clazz.newInstance();
Method m_setH=clazz.getMethod("setH", int.class);
m_setH.invoke(r2, 20);
Method m_setW=clazz.getMethod("setW", int.class);
m_setW.invoke(r2, 40);
Method m_length=clazz.getMethod("length");
int l=(int)m_length.invoke(r2);
System.out.println(l);
}
}
//
package aaa;
public class Rectangle{
private int w=10;// 宽
private int h;// 长
public int i;
public Rectangle() {
super();
}
public Rectangle(int w, int h) {
super();
this.w = w;
this.h = h;
}
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
// 周长
public int length() {
return 2 * (this.w + this.h);
}
// 面积
public int area() {
return w * h;
}
}