2020-09-20 方法

1.method的常用方法

1.1 以整数形式返回此 Method 对象所表示方法的 Java 语言修饰符。

	int getModifiers() 
	@Test
    public void test1() throws Exception {
        Class clazz = ArrayList.class;
        Method method1 = clazz.getMethod("size");
        int k = method1.getModifiers();
    }

1.2 返回一个 Class 对象,该对象描述了此 Method 对象所表示的方法的正式返回类型。

	Class<?> getReturnType()  
	@Test
    public void test1() throws Exception {
        Class clazz = ArrayList.class;
        Method method1 = clazz.getMethod("size");        
        Class c = method1.getReturnType();
    }

1.3 以 String 形式返回此 Method 对象表示的方法名称。

	String getName()  
	@Test
    public void test1() throws Exception {
        Class clazz = ArrayList.class;
        Method method1 = clazz.getMethod("size");
        String s = method1.getName();
    }

1.4 按照声明顺序返回 Class 对象的数组,这些对象描述了此 Method 对象所表示的方法的形参类型。

	Class<?>[] getParameterTypes()  
	@Test
    public void test1() throws Exception {
        Class clazz = ArrayList.class;
        Method method1 = clazz.getMethod("size");
        Class[] classes = method1.getParameterTypes();
    }

1.5 返回 Class 对象的数组,这些对象描述了声明将此 Method 对象表示的底层方法抛出的异常类型。

	Class<?>[] getExceptionTypes()  
	@Test
    public void test1() throws Exception {
        Class clazz = ArrayList.class;
        Method method1 = clazz.getMethod("size");
        Class[] classes1 = method1.getExceptionTypes();
    }

1.6 如果存在该元素的指定类型的注释,则返回这些注释,否则返回 null。

	<T extends Annotation> T  getAnnotation(Class<T> annotationClass)  
	@Test
    public void test1() throws Exception {
        Class clazz = ArrayList.class;
        Method method1 = clazz.getMethod("size");
        Annotation[] classes2  =method1.getAnnotations();
    }

1.7 执行方法

当执行私有方法时,还需要设置method1.setAccessible(true);

	Object invoke(Object obj, Object... args)  
	@Test
    public void test1() throws Exception {
        Class clazz = ArrayList.class;
        Method method1 = clazz.getMethod("size");
        Method method2 = clazz.getMethod("add",Object.class);        
        Object o = clazz.newInstance();
        Object o1 = method1.invoke(o);
        Object o2 = method2.invoke(o,"add");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值