Java--反射

1.什么是反射?

反射是框架设计的灵魂,框架:它是一个半成品,可以拿来使用,添加上自己的业务代码。提高开发效率。

反射就是把类中成员抽取成其他类的过程。这就是反射。

2.如何获取反射类对象--Class

(1) 通过Class.forName获取反射对象.

Class.forName("全路径")
--spring它就是使用的该模式<bean class="全路径">

(2)通过类名.class获取

类名.class;

---代理类--->SqlSession.getMapper(StudentDao.class)

(3) 通过对象.getClass()方法获取

对象.getClass(); ---当知道对象时可以通过这种方式获取反射对象
public class Test01 {
    public static void main(String[] args) throws ClassNotFoundException {
        //1.通过Class.forName来获取反射类对象。
        Class aClass = Class.forName("demo.People");
        //2.通过类名调用.class获取反射类对象
        Class aClass1 = People.class;
        //3.通过对象获取反射类对象
        People p=new People();
        Class aClass2 = p.getClass();

        //思考:上面三个反射对象的引用地址是否一致! 是一致的。 一个类只会被加在到内存中一次。
        System.out.println(aClass==aClass1);
        System.out.println(aClass2==aClass1);
    }
}

3.通过反射类获取对应的类对象。

aclass.newInstance();

public class Test02 {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        //1.获取反射类对象
        Class<People> aClass = People.class;
        //2.由反射类创建类对象---调用为无参构造函数
        People people = aClass.newInstance();
        People people2 = aClass.newInstance();

        //3.他们的地址是否相同
        System.out.println(people==people2);
    }
}

4.通过反射获取对应的Field属性对象。

public class Test {
    public static void main(String[] args) throws Exception {
        Class<?> aClass = Class.forName("demo.People");

        //获取本类中指定的属性对象
        Field name = aClass.getDeclaredField("name");
        System.out.println(name);
        //获取本类以及父类中指定的属性---必须为public修饰的。
        Field name1 = aClass.getField("sex");
        System.out.println(name1);

        //获取本类中所有的属性对象
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field:declaredFields) {
            System.out.println(field);
        }

        //获取本类以及父类中所有public修饰的属性对象
        Field[] fields = aClass.getFields();
        for (Field field:
             fields) {
            System.out.println(field);
        }

    }
}

5.Field属性对象中常见的方法

getName():获取属性名
setAccessible(true):设置属性可访问。
set(o,v):为对象o的属性赋值v
get(o):获取对象o的属性值

public static void main(String[] args) throws Exception {
        Class<People> peopleClass = People.class;

        Field nameField = peopleClass.getDeclaredField("name");
        //1.获取属性的名称
        String name = nameField.getName();
        System.out.println("属性名称:"+name);

        //2.为属性赋值.
        //Object obj,对象
        // Object value
        People people = peopleClass.newInstance();
        System.out.println(people);

        nameField.setAccessible(true);//为nameField设置可访问权限,打破了封装性
        nameField.set(people,"张三");
        System.out.println(people);

        //3.获取属性值
        Object o = nameField.get(people);
        System.out.println(o);

        //nameField.getAnnotation();//获取nameField属性上的注解对象
    }

6.通过反射获取对应的Method方法对象

public class Test03 {
    public static void main(String[] args) throws Exception {
        Class<People> aClass = People.class;

        //获取本类中所有的方法。
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method:declaredMethods) {
            System.out.println(method);
        }


        System.out.println("======================================================");
        //获取本类和父类中所有public修饰的方法
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }

        System.out.println("**************************************************************");
        //本类中指定的 方法对象
        Method fun = aClass.getDeclaredMethod("fun");
        System.out.println(fun);
        Method setName = aClass.getDeclaredMethod("setName",String.class);
        System.out.println(setName);

        //获取本类以及父类中指定名称的方法对象
        Method equals = aClass.getMethod("equals", Object.class);
        System.out.println(equals);

    }
}

7.Method类中常见的方法

  //method.invoke(对象,方法参数值);
 invoke(people,"15");//回调。动态代理

8. 获取相应注解对象

public class Test {
    public static void main(String[] args) throws Exception{
        Class<Student> aClass = Student.class;

        //获取类对象的指定注解
        MyAnnotation annotation = aClass.getAnnotation(MyAnnotation.class);
        System.out.println(annotation.value());


        Field idField = aClass.getDeclaredField("id");
        MyAnnotation annotation1 = idField.getAnnotation(MyAnnotation.class);
        System.out.println(annotation1.value());
        System.out.println(annotation1.sex());

    }
}

9. 手撕ORM框架

ORM:(Object relative Mapping)对象关系映射框架。帮你自动把数据库中的记录和java实体类对应映射在一起。

修改。删除

public class BaseDao<T>{
    //修改的方法
    // update 类名 set name=值 where id=值
    public int update(T t) {

        StringBuffer sb = new StringBuffer(" update ");
        //1.获取反射对象
        Class<?> aClass = t.getClass();
        //获取注解
        com.wjk.annotation.TableName tableName = aClass.getAnnotation(com.wjk.annotation.TableName.class);
        String value = "";
        if (tableName != null) {
            //获取注解的值
            value = tableName.value();
        } else {
            //获取类名
            value = aClass.getName();
        }
        sb.append(value + " set ");

        Connection connection=null;
        PreparedStatement ps=null;
        //获取属性名和值
        try {
            //获取反射类中所有的属性
            Field[] declaredFields = aClass.getDeclaredFields();
            String where = " where ";
            for (Field declaredField : declaredFields) {

                declaredField.setAccessible(true);

                IdAnnotation annotation1 = declaredField.getAnnotation(IdAnnotation.class);
                if (annotation1 != null) {

                    where += annotation1.value() + "=" + declaredField.get(t);

                } else {
                    //获取注解
                    com.wjk.annotation.TableField annotation = declaredField.getAnnotation(com.wjk.annotation.TableField.class);
                    if (annotation != null) {
                        //获取注解的值--列
                        sb.append(annotation.value() + "='" + declaredField.get(t) + "',");
                    } else {

                        sb.append(declaredField.getName() + "='" + declaredField.get(t) + "',");
                    }
                }

            }
            //截取
            String str = sb.substring(0, sb.lastIndexOf(","));

            String i = str + where;
            System.out.println(i);
            //获取链接对象
            Connection conn = DBUtills.getConn();
            //sql
            ps=conn.prepareStatement(i.toString());
            //执行sql
            int i1 = ps.executeUpdate();
            return i1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtills.closeAll(null,ps,connection);

        }
        return 0;
    }

    //增加
    public int insert(T t) throws Exception{

        StringBuffer sb=new StringBuffer(" insert into ");
        //获取表名
        Class<?> aClass = t.getClass();
        TableName tableNameAnnotation = aClass.getAnnotation(TableName.class);
        String tableName="";
        //是否存在该注解
        if (tableNameAnnotation!=null) {
             tableName = tableNameAnnotation.value();
        }else {

        tableName=aClass.getSimpleName();
        }
        //添加表名
        sb.append(tableName);
        //获取反射类对象中所有的属性对象
        Field[] declaredFields = aClass.getDeclaredFields();
        List<String> columns=new ArrayList<String>();
        List<String>  values=new ArrayList<String>();

        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            TableField tableField = declaredField.getAnnotation(TableField.class);
            if (tableField!=null){
                    columns.add(tableField.value());
            }else {
                columns.add(declaredField.getName());
            }
                values.add("'"+declaredField.get(t)+"'");

        }
            sb.append(columns.toString().replace("[","(").replace("]",")"));
            sb.append(" values ");
            sb.append(values.toString().replace("[","(").replace("]",")"));

        System.out.println(sb);

        Connection conn = DBUtills.getConn();
        PreparedStatement ps = conn.prepareStatement(sb.toString());
        int i = ps.executeUpdate();

        return i;

    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值