反射代码块
来源:互联网 发布:c语言的头文件怎么写 编辑:程序博客网 时间:2024/06/06 18:38
代码示例package com.atguigu.reflect;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;public class ReflectTest { public static void main(String[] args) { try { Class<?> clazz = Class.forName("com.atguigu.reflect.Student"); Object object = clazz.newInstance(); Field f1_age = clazz.getDeclaredField("age"); f1_age.setAccessible(true); f1_age.set(object, 20); System.out.println(object); Method method = clazz.getMethod("add", int.class,double.class); Object invoke = method.invoke(object, 100,20.22); System.out.println(invoke); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }}abstract class Parent<T> { private Class clazz; public Parent() { Type type = getClass().getGenericSuperclass(); if(type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; Type[] types = ptype.getActualTypeArguments(); clazz = (Class) types[0]; } else { clazz = Object.class; } }}class Child extends Parent<Integer> {}class Child2 extends Parent{}Entitypackage com.atguigu.javase.reflect;public class Student { private static String school = "atguigu"; private String name; private int age; public Student() { } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } public static int add(int x, double y) { return x + (int)y; }}
阅读全文
0 0
- Java反射代码块
- 反射代码块
- 反射代码块,自己理解
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- 代码块
- MFC中 OnPaint()与OnDraw的区别
- mysql事务简述
- TCP协议中的URG和PSH标志位的区别
- Socket复制文件编程Demo
- TCP的三次握手与四次挥手
- 反射代码块
- SQL Server 中WITH (NOLOCK)浅析(大自然的搬运工)
- Map的排序Demo
- 图像处理动机(课堂笔记)
- MFC UpdateData()用法
- redis集群安装踩过的坑
- 编译安装PHP
- 刷清橙OJ--A1084.快速傅里叶变换
- 2017-04-26 每日一记 C语言API