`
shoushounihao
  • 浏览: 39505 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

反射机制

    博客分类:
  • java
阅读更多

package com.itcast.demo;

import java.io.ObjectInputStream.GetField;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.itcast.bean.Person;

public class Demo1 {

 /**
  * @param args
  * @throws ClassNotFoundException
  * @throws IllegalAccessException
  * @throws InstantiationException
  * @throws InvocationTargetException
  * @throws IllegalArgumentException
  * @throws NoSuchMethodException
  * @throws SecurityException
  */
 public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchMethodException {
  Class<?> clazz=Class.forName("com.itcast.bean.Person");
  
  System.out.println("完整路径名称:   "+clazz.getName());
  
  Person per1=(Person)clazz.newInstance();//进行无参数构造
  Person per3=null;
  Person per2=null;
  //构造参数(必须先初始化无参数,再初始化有参数的)
//  System.out.println("构造参数(必须先初始化无参数,再初始化有参数的)");
//  Constructor<?> cons[]=clazz.getConstructors();
//  per2=(Person)cons[0].newInstance();
//  per3=(Person)cons[1].newInstance("xiaoming");
  
  
  
  
  System.out.println("声明的属性");
  Field [] fd=clazz.getDeclaredFields();
  for(int i=0;i<fd.length;i++)
  {
   Class<?> type=fd[i].getType();
   System.out.println("类型属性"+type.getName()+" 字段名称 "+fd[i].getName());
  }
  
  
  //获取对应的方法
  Method method=clazz.getMethod("sysHello");
  method.invoke(clazz.newInstance());
  //获取带有参数的方法
  method=clazz.getMethod("sysGoodbye", String.class);
  method.invoke(clazz.newInstance(),"灵感");
  
  
  System.out.println("接口.............");
  
  
  Class<?>  intes[]=clazz.getInterfaces();
  if(intes.length>0){
   
   for(int i=0;i<intes.length;i++)
   {
    System.out.println(intes[i].getName());
   }
  }

  
  System.out.println("获取构造方法............");
  
  Constructor<?> cons[]=clazz.getConstructors();
  if(cons.length>0)
  {
   for(Constructor con:cons)
   {
    System.out.println(con);
   }
  }
  
  
 }

}

 

对应实体对象

package com.itcast.bean;

public class Person {

 
 public Person(){}
 public Person(String userName){this.userName=userName;System.out.println(userName);}
 
 private int age;
 private String userName;
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 
 
 public void sysHello(){System.out.println("欢迎小明........");}
 public void sysGoodbye(String ss){System.out.println(ss+"  坏人");}
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics