package cn.hncu.reflect.hello;
import java.lang.reflect.Method;
public class ReflectHelloWorld {
public static void main(String[] args) {
//类反射的入口是Class c
try {
Class<?> c=Class.forName("cn.hncu.reflect.hello.Person");//参数必须是类全名
//Method ms[]=c.getMethods();//获取当前类及其父类的所有public方法
Method ms[]=c.getDeclaredMethods();//只是获取当前类自己定义的所有方法(包括private及其它权限)
for(Method m:ms){
System.out.println(m);
System.out.println("------------------");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public interface USB {
public void work();
}
import java.io.InputStream;
import java.util.Properties;
public class USBFactory {
public static USB getUSB() throws Exception{
Properties p=new Properties();
//FileInputStream fin=new FileInputStream("bin\\cn\\hncu\\reflect\\hello\\usb\\usb.config");
InputStream fin=USBFactory.class.getClassLoader().getResourceAsStream("bin\\cn\\hncu\\reflect\\hello\\usb\\usb.config");
p.load(fin);
String nm= p.getProperty("name");
Class<?> c=Class.forName(nm);
return (USB) c.newInstance();
}
}
public class Client {
public static void main(String[] args) {
USB usb=null;
try {
usb = USBFactory.getUSB();
usb.work();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import cn.hncu.reflect.hello.usb.USB;
public class UsbOne implements USB{
@Override
public void work() {
System.out.println("UsbOne............");
}
}
import cn.hncu.reflect.hello.usb.USB;
public class UsbTwo implements USB{
@Override
public void work() {
System.out.println("UsbTwo............");
}
}
import cn.hncu.reflect.hello.usb.USB;
public class UsbMouse implements USB{
@Override
public void work() {
System.out.println("UsbMouse........");
}
}
public class SimulateInstanceof {
public static void main(String[] args) throws Exception {
// boolean b=new B() instanceof B;
String className = "cn.hncu.reflect.simulate.B";
Class<?> c = Class.forName(className);// 模板对象c
boolean b1 = c.isInstance(new A());
System.out.println(b1);
B obj1 = new B();
B obj2 = new B();
System.out.println(c.isInstance(obj1));
System.out.println(c.isInstance(obj2));
}
}
import org.junit.Test;
import cn.hncu.reflect.hello.Person;
/*
* 获取Class模板对象的三种方式
*/
public class ReflectGetClass {
// 法1:通过对象的getClass方法进行获取
@Test
public void test1() {
Person p = new Person("aaa", 12);
Class c = p.getClass();// Object中的方法
}
// 法2: 任何数据类型(包括基本数据类型)都具备着一个静态的属性class,通过它可直接获取到该类型对应的Class对象。
@Test
public void test2() {
Class c1 = Person.class;
Class c2 = Integer.class;
Class c3 = int.class;
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
}
// 法3: 通过Class.forName()方法获取。
@Test
public void test3() throws Exception {
String className="cn.hncu.reflect.simulate.B";
Class<?> c=Class.forName(className);
System.out.println(c);
}
}