反射的简单用例--1

/**
 * 
 */
package com.reflection;

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

import org.junit.Test;

/**
 * @author lihai 
 * @createdtime 2018-5-8 下午11:11:51
 * @类描述
 */
public class RefDemo {
	
	@Test
	public void getMethodClass() throws InstantiationException, 
	IllegalAccessException, SecurityException, NoSuchMethodException, 
	IllegalArgumentException, InvocationTargetException{
		//
		Class<?> c = methodClass.class;
		Object object1 = c.newInstance();//使用Class对象的newInstance()方法来创建Class对象对应类的实例
		
		//getMethods()方法返回类的所有公用方法,包括其继承类的公用的方法
		//Method[] methods = c.getMethods();
		//getDeclaredMethods()方法返回类或接口声明的所有方法,包括公共,保护,默认访问和私有方法,不包括继承的方法
		//Method[] declareMethods = c.getDeclaredMethods();
		//获取methodClass类的add方法
		Method method = c.getMethod("add", int.class,int.class);
		
		Object result = method.invoke(object1, 1,5);
		System.out.println(result);
		
		
		/*for(Method method2 : methods){
			System.out.println(method2);
		}
		System.out.println("-------------------------------------------------------------");
		for(Method method2 : declareMethods){
			System.out.println(method2);
		}*/

		
	}
	
	/**
	 * 利用反射创建数组
	 * @throws ClassNotFoundException 
	 */
	@Test
	public void createArrayByRef() throws ClassNotFoundException{
		Class<?> class1 = Class.forName("java.lang.String");
		Object array = Array.newInstance(class1, 25);
		Array.set(array, 0, "ttt");
		Array.set(array, 1, "rrr");
		Array.set(array, 2, "eee");
		Array.set(array, 3, "www");
		Array.set(array, 4, "qqq");
		System.out.println(Array.get(array, 3));
	}
}
class methodClass{
	public final int juce=3;
	public int add(int a,int b){
		return a+b;
	}
	public int sub(int a,int b){
		return a+b;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值