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());
    		}
    	
    		
    	}
    }
    


  • 相关阅读:
    最大流之dinic
    HDU 2485
    最小费用最大流
    HDU 1533
    HDU 1402
    HDU 1498
    HDU 1281
    Codeforces 283E Cow Tennis Tournament 线段树 (看题解)
    Codeforces 983E NN country 思维 (看题解)
    Codeforces 494D Birthday 树形dp (看题解)
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720419.html
Copyright © 2011-2022 走看看