java基础反射的学习

反射学习,所有基础都很重要
认识Class类
    public final Class getClass()
以上方法返回值得类型是一个Class类,实际上此类事Java反射的源头,
正常方式:引入需要的包.类 --->通过new实例化--->取得实例化对象
反射方式:实例化对象→ getClass()-->得到完整的包类名称
    java中Object是一切类的父类,那么所有类的对象实际上也就是java.lang.Class类的
实例
class X{

    }
    public class TestClass {

public static void main(String[] args) {
Class<?> class1 =null;
Class<?> class2=null;
Class<?> class3 =null;
try {
   class1 = Class.forName("com.test.ll.X");
System.out.println(class1.toString());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
class2= new X().getClass();
System.out.println(class2.toString());
class3=X.class;
System.out.println(class3.toString());
}
}
Class类本身表示一个类的本身,此类中的方法定义、属性定义等
Class类的使用
    通过无参构造实例化对象
public class Person {
    private int age;
    private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}
public void sayHello(){
System.out.println("heihei");
}
public void sayHello1(String name,int i){
System.out.println("name"+name+"======"+i);
}
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> c=null;
Class<?> forName = Class.forName("com.test.ll.Person");
//这种方式需要有无参构造器,否则会抛出异常
Person p =(Person) forName.newInstance();
p.setAge(5);
p.setName("haha");
System.out.println(p);
}
}
通用有参函数构造实例化对象
public class Person1 {
private int age;
private String name;
public Person1(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> c=null;
c=Class.forName("com.test.ll.Person1");
//获取所有构造器
Constructor<?>[] constructors = c.getConstructors();
for (int i = 0; i < constructors.length; i++) {
Constructor<?> constructor = constructors[i];
System.out.println(constructor.toString());
}
Person1 p =(Person1) constructors[0].newInstance(30,"llll");
System.out.println(p);
//获取类中所有的全部接口
Class<?>[] interfaces = c.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
System.out.println(interfaces[i].toString());
}
//获取父类
Class<?> superclass = c.getSuperclass();
System.out.println(superclass.toString());
}
}
反射的应用取得类的结构
    Construtor :表示构造方法
Field:表示类的属性
public class Testfield {
//反射操作属性
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
Class<?> c =null;
c =Class.forName("com.test.ll.Person");
Person p = (Person) c.newInstance();//创建实例
Field fieldName=null;
Field fieldAge=null;
fieldName=c.getDeclaredField("name");
fieldAge=c.getDeclaredField("age");
fieldName.setAccessible(true);//将name 设置外部可调用
fieldName.set(p, "hi girl");
fieldAge.setAccessible(true);//将age 设置外部可调用
fieldAge.set(p, 16);
System.out.println(fieldName.get(p));
System.out.println(fieldAge.get(p));
}
}
Method :表示类的方法
public class TestMethod {
//反射调用方法
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> c =Class.forName("com.test.ll.Person");
Method method = c.getMethod("sayHello1",String.class,int.class);
/* try {
method.invoke(c.newInstance());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
method.invoke(c.newInstance(), "girl",18);
}
}
通过反射调用方法
    通过方法操作属性
    public class HUO {
private int age;
private String name;


public HUO(int age, String name) {
super();
this.age = age;
this.name = name;
}


public int getAge() {
return age;
}


public void setAge(int age) {
this.age = age;
}


public String getName() {
return name;
}
        public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> c=null;
c=Class.forName("com.test.ll.Person1");
//获取所有构造器
Constructor<?>[] constructors = c.getConstructors();
for (int i = 0; i < constructors.length; i++) {
Constructor<?> constructor = constructors[i];
System.out.println(constructor.toString());
}
   Field[] fields = c.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
//获取属性类型
Class<?> type = fields[i].getType();
System.out.println(type.toString());
int modifiers = fields[i].getModifiers();
System.out.println(modifiers);
String name2 = fields[i].getName();
System.out.println(name2.toString());
}
}
}
   public class TestArr {

//反射操作数组
    public static void main(String[] args) {
int temp[] ={1,5,6};
Class<?> c= temp.getClass().getComponentType();
System.out.println(c.getName());//数组的名字
System.out.println(Array.getLength(temp));//数组的长度
Array.set(temp, 0, 6);//change value
System.out.println(Array.get(temp, 0));
}
}
反射应用动态代理
    public interface Subject {
    public String sayHi(String name);
}
    public class RealSubject  implements Subject{
@Override
public String sayHi(String name) {  
return "hi,beatiful girl";
}
public static void main(String[] args) {
//创建代理类参数  //应用例如springaop,打印日志
MyInvocationHandler handler = new MyInvocationHandler();
RealSubject sub = new RealSubject();
//实例化代理类
Subject bind =   (Subject) handler.bind(sub);
String sayHi = bind.sayHi("hhh");
System.out.println(sayHi);
}
}  
    public class MyInvocationHandler implements InvocationHandler{
    private Object obj;
    
public Object bind(Object obj) {
this.obj=obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}


@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   
return method.invoke(this.obj, args);
}
}
反射在工厂中的应用
    interface Fruit{
public void eat();
}
class Apple implements Fruit{
@Override
public void eat() {
System.out.println("吃苹果...");
}
}
class Factory{
public static Fruit getInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
Class<?> forName = Class.forName(className);
return  (Fruit) forName.newInstance();
}
}
public class TestFactory {
//将反射应用到工厂
public static void main(String[] args) {
try {
Fruit instance = Factory.getInstance("com.test.ll.Apple");
if(instance!=null){
instance.eat();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

猜你喜欢

转载自blog.csdn.net/yl_hahha/article/details/80188512
今日推荐