java反射事例

UserInfo  类;

public class UserInfo {

 public String name;
 private String age;
 protected String sex;
 
 public UserInfo(){
  
 }
 public UserInfo(String name){
  this.name=name;
 }
 public void say(String name){
  System.out.println(name+"说:XX");
 }
 
 private int add(int i,int j){
  return i+j;
 }
 
 protected String hello(){
  return "Hello World!";
 }
 public String toString(){
  return name;
 }
}

 

 

--------------------------------------------------------------------------------------------------------

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class FlectTest {

 /**
  * @param args
  * @throws ClassNotFoundException
  * @throws IllegalAccessException
  * @throws InstantiationException
  * @throws SecurityException
  * @throws NoSuchMethodException
  * @throws InvocationTargetException
  * @throws IllegalArgumentException
  * @throws NoSuchFieldException
  */
 public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
  /*Class cla=
    Class.forName("date2.reflect.UserInfo");//通过字符串找到类
  
  //获取当前类及其父类中public修饰的方法
//  Method[] methods=cla.getMethods();
  //获取当前类中出现的方法,父类中的方法获取不到
  Method[] methods=cla.getDeclaredMethods();
  for (Method method : methods) {
   System.out.println(method.getName());
  }
  Object obj=cla.newInstance();
  Method method=cla.getDeclaredMethod("add",
    int.class,int.class);
  method.setAccessible(true);
  Object s=method.invoke(obj, 12,34);

  System.out.println(s);
  
  System.out.println("=====================");
  Field[] fields=cla.getDeclaredFields();
  for (Field field : fields) {
   //System.out.println(field.getName()+":"+field.getType().getName());
   
  }
  Field field=cla.getDeclaredField("age");
  field.setAccessible(true);
  //如果该对象为static在不用指明obj,为null
  field.set(obj, "zhang san");
  Object value=field.get(obj);
  System.out.println(value);
  System.out.println("--------------");
  Constructor cons=
    cla.getDeclaredConstructor(String.class);
  Object o=cons.newInstance("accp");
  System.out.println(o);
  
  
  
 */

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值