zoukankan      html  css  js  c++  java
  • java_jdbc_反射

    package cn.itcast.Reflect;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class ReflectDemo {
    
    	public static void main(String[] args) throws Exception {
    		// TODO Auto-generated method stub
    		Class clazz = User.class;
    		
    		Object obj=create(clazz);
    		
    		System.out.println(obj);
    		
    		invoke1(obj,"showMessage");
    		System.out.println("-------------------------");
    		field(clazz);
    	}
    	//创建对象
    	static Object create(Class clazz) throws Exception{
    		Constructor con = clazz.getConstructor(String.class);
    		Object obj  = con.newInstance("test name");	
    		return obj;
    		
    	}
    	
    	//调用方法
    	static void invoke1(Object obj,String methodName) throws Exception{
    		
    		Method[] ms = obj.getClass().getMethods();
    		for(Method m:ms){
    			System.out.println(m.getName());
    			if(methodName.equals(m.getName())){
    				m.invoke(obj, null);
    			}
    		}
    		
    		Method m = obj.getClass().getMethod(methodName, null);
    		m.invoke(obj, null);
    	}
    
    	static void field(Class clazz) throws Exception{
    		
    		Field[] fs = clazz.getDeclaredFields();
    		//不会便利出私有变量
    //		fs = clazz.getFields();
    		for(Field f : fs){
    			
    			System.out.println(f.getName());
    		}
    	
    		
    	}
    }
    


  • 相关阅读:
    python 字典
    python 列表
    被闭包啪啪啪的打脸之 闭包的错误使用
    TCP的三次握手和四次挥手
    传输层的TCP和UDP协议
    个人小程序应用开发指南
    ES2019 / ES10有什么新功能?
    CSS开启硬件加速来提高网站性能
    js中this的指向问题
    Js面向对象构造函数继承
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720419.html
Copyright © 2011-2022 走看看