• 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相关遗漏知识点补充
    关于viewpager的滑动问题
    C++学习一二
    Neo4j 爬坑笔记for3.2.6
    ZTree简单粗暴快速使用
    阅读HashMap——jdk7时遇到的问题记录
    【安装】Hadoop2.8.0搭建过程整理版
    html、jsp页面标签的遍历
    tomcat配置多个数据源
    java线程
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720419.html
Copyright © 2020-2023  润新知