import java.io.*;
import java.lang.reflect.*;
class father{
public String fName;
father(String name) {
this.fName = name;
}
public void show() throws Exception{
Runtime.getRuntime().exec("touch 2.txt");
}
}
class child extends father{
public int cAge;
child(int age,String name){
super(name);
this.cAge = age;
}
public void display() {
System.out.println("I am Child!");
}
}
对运行时候的对象调用getClass获取其类对象
public class InvokeLearn{
public static void main(String[] args) throws Exception{
father f = new father("TOM");
child c = new child(5,"JIM");
String clsname = c.getClass().getName();//可以获取类,然后getName返回类名字符串
System.out.println(clsname);
}
}
对类本身调用class属性
public class InvokeLearn{
public static void main(String[] args) throws Exception{
//Runtime.getRuntime().exec("touch 1.txt");
father f = new father("TOM");
child c = new child(5,"JIM");
String clsname = c.getClass().getName();
Class<child> clsname1 = child.class;
System.out.println(clsname1.getName());
}
}
使用Class.forName()方法
public class InvokeLearn{
public static void main(String[] args) throws Exception{
//Runtime.getRuntime().exec("touch 1.txt");
father f = new father("TOM");
child c = new child(5,"JIM");
Class cls = Class.forName("father");
}
}
public class InvokeLearn{
public static void main(String[] args) throws Exception{
Class cls = Class.forName("father");
Constructor[] conArray= cls.getDeclaredConstructors();//所有构造方法
/*
* getConstructors() ->所有公有的构造方法
* getConstructors(null) -> 所有公有的无餐的构造方法
* getDeclaredConstructor(parameters_type) -> 私有的含参的构造方法,parameters_types是参数的类型
*/
//System.out.print(conArray.length);
Constructor newc = conArray[0];
Object obj = newc.newInstance("Tom");//调用构造方法创建实例
}
}
public class InvokeLearn{
public static void main(String[] args) throws Exception{
Class cls = Class.forName("father");
Constructor[] conArray= cls.getDeclaredConstructors();//所有构造方法
Constructor newc = conArray[0];
Object obj = newc.newInstance("Tom");//创建实例
Field dis = cls.getDeclaredField("fName");//获取属性对象
dis.set(obj,"George");//设置属性值
System.out.println(dis.get(obj));//获取属性值并打印
}
}
public class InvokeLearn{
public static void main(String[] args) throws Exception{
Class cls = Class.forName("father");
Constructor[] conArray= cls.getDeclaredConstructors();//所有构造方法
Constructor newc = conArray[0];
Object obj = newc.newInstance("JJJ");//创建实例
Method dis = cls.getDeclaredMethod("show",null);//获取show方法
dis.invoke(obj, null);//调用show方法
}
}