泛型与反射

来源:互联网 发布:java apache发邮件 编辑:程序博客网 时间:2024/05/16 10:39
  1. 泛型
    泛型的作用  

      泛型是JDK1.5以后才有的,可以在编译时期进行类型检查,且可以避免频繁类型转化!


    泛型的使用
      泛型的方法:
    public class GenericDemo {// 定义泛型方法public <K,T> T save(T t,K k) {return null;}// 测试方法@Testpublic void testMethod() throws Exception {// 使用泛型方法:  在使用泛型方法的时候,确定泛型类型save(1.0f, 1);}}
      泛型的类:
    public class GenericDemo<T> {// 定义泛型方法public <K> T save(T t,K k) {return null;}public void update(T t) {}// 测试方法@Testpublic void testMethod() throws Exception {// 泛型类:  在创建爱泛型类对象的时候,确定类型GenericDemo<String> demo = new GenericDemo<String>();demo.save("test", 1);}}
      泛型的接口:
    /** * 泛型接口 * @author Jie.Yuan * * @param <T> */public interface IBaseDao<T> {void save(T t );void update(T t );}泛型接口类型确定: 实现泛型接口的类也是抽象,那么类型在具体的实现中确定或创建泛型类的时候确定public class BaseDao<T> implements IBaseDao<T> {泛型接口类型确定: 在业务实现类中直接确定接口的类型public class PersonDao implements IBaseDao<Person>{


      泛型的关键字:?,extends,super
                    ?             指定只是接收值

    extends      元素的类型必须继承自指定的类

    super        元素的类型必须是指定的类的父类

  2. 反射
    什么是反射?

    反射,可以在运行时期动态创建对象;获取对象的属性、方法;

    反射怎么用?
    <span style="font-size:18px;">/** *  */package com.tan.reflect;import java.lang.reflect.Field;import java.lang.reflect.Method;import org.junit.Test;/** * 功能: * @author TanZi * @time 2015-5-25上午11:11:45 */public class App {@Testpublic void test(){String className="com.tan.reflect.Admin";//运行时创建对象try {Class<?> clazz=Class.forName(className);//-------------获取构造器/* * 方法一: * 创建对象:默认构造函数简写 * Admin admin=(Admin) clazz.newInstance(); *  */Admin admin=(Admin) clazz.newInstance();/* * 方法二: * 通过带参数的构造器对象 * Constructor<?> constructor=clazz.getDeclaredConstructor(); * Admin admin=(Admin) constructor.newInstance("方法二"); *  *///--------------获取所有的属性名称Field[] fs=clazz.getDeclaredFields();for(Field f:fs){//设置强制访问f.setAccessible(true);//获取属性名称System.out.println(f.getName());//获取属性的值    System.out.println(f.get(admin));}//-----------------获取方法----------------Method method=clazz.getDeclaredMethod("getId");System.out.println("method.invoke(admin):"+method.invoke(admin));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }}</span>





0 0