黑马程序员_反射、内省、注解

1.Class  

   概述:实际上就是管理java类的,比如说管理人的用Person类,那么管理类的就是用的是Class类。

2.创建对象和使用

    因为Class类中没有构造方法,不能创建对象,但是每一个java类都会产生一个字节码对象,它会将字节码对象赋给Class变量。例如:String,Math,Date等等这些类都会产生一个个的字节码,他们就对应着一个个的Class类对象,只要拿到的这些类的字节码就可以对这个类进行操作了。

     拿到字节码有三种方式:

      第一种:Class clazz=Class.forName(“java.lang.String”);

      第二种:Class clazz=new String().getClass();

      第三种:Class clazz=String.class.

3.预定义的Class

  包括八种基本类型:(byte、short、int、long、float、double、char、boolean)
         的字节码对象和一种返回值为void类型的void.class。

4.基本数据类型的字节码都可以用与之对应的包装类中的TYPE常量表示

  Integer.TYPE是Integer类的一个常量,它代表此包装类型包装的基本类型的字节码,
    所以和int.class是相等的。

5.下面是对类的各个成分进行反射:

反射字段:假设我已经定义好了一个Person类

(1) 反射私有字段:

 Field[] field=Class.forName("javalx.Person").getDeclaredFields();
for(Field f:field)
{
<span style="white-space:pre">	</span>f.setAccessible(true);
<span style="white-space:pre">	</span>System.out.println(f.get(p));
}
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);">(2)反射公有字段: </span>

<span style="white-space:pre">	</span> Field fieldname = Class.forName("javalx.Person").getField("name");
<span style="white-space:pre">	</span> System.out.println((String)fieldname.get(p));

(3)反射构造函数:

1)反射空参数的构造函数:   

<span style="white-space:pre">	</span>Constructor constructor=Class.forName("javalx.Person").getConstructor(null);
<span style="white-space:pre">	</span>String s=constructor.getName();
<span style="white-space:pre">	</span>Person p=(Person)constructor.newInstance(null);
<span style="white-space:pre">	</span>Field[] field=
<span style="white-space:pre">	</span>Class.forName("javalx.Person").getDeclaredFields();
<span style="white-space:pre">	</span>for(Field f:field)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>f.setAccessible(true);
<span style="white-space:pre">			</span>System.out.println(f.get(p));
<span style="white-space:pre">	</span>}

2) 反射带有一个参数的构造函数

<span style="white-space:pre">	</span>Constructor constructor1=Class.forName("javalx.Person").getConstructor(String.class,int.class);
<span style="white-space:pre">	</span>Person p1=(Person) constructor1.newInstance("lisi",23);
<span style="white-space:pre">	</span>Field[] field1=
<span style="white-space:pre">	</span>Class.forName("javalx.Person").getDeclaredFields();
<span style="white-space:pre">	</span>for(Field f:field1)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">	</span>f.setAccessible(true);
<span style="white-space:pre">	</span>System.out.println(f.get(p1));
<span style="white-space:pre">	</span>}

3)反射带有private的构造函数

<span style="white-space:pre">	</span>Constructor constructor11=Class.forName("javalx.Person").getDeclaredConstructor(String.class,int.class);
<span style="white-space:pre">	</span>constructor11.setAccessible(true);
<span style="white-space:pre">	</span>Person p11=(Person) constructor11.newInstance("lisi",23);
<span style="white-space:pre">	</span>Field[] field11=Class.forName("javalx.Person").getDeclaredFields();
<span style="white-space:pre">	</span>for(Field f:field11)
<span style="white-space:pre">	</span>{
    <span style="white-space:pre">		</span>f.setAccessible(true);
    <span style="white-space:pre">		</span>System.out.println(f.get(p11));
<span style="white-space:pre">	</span>}

(4)反射方法

1)反射空参数的方法

<span style="white-space:pre">	</span>Constructor constructor=Class.forName("javalx.Person").getConstructor(null);
<span style="white-space:pre">	</span>String s=constructor.getName();
<span style="white-space:pre">	</span>Person p=(Person)constructor.newInstance(null);
<span style="white-space:pre">	</span>Method method=
<span style="white-space:pre">	</span>Class.forName("javalx.Person").getMethod("show",null);
<span style="white-space:pre">	</span>method.invoke(p, null);*/

2)反射带有一个参数的方法

<span style="white-space:pre">	</span>Person p=new Person();
<span style="white-space:pre">	</span>Method method=
<span style="white-space:pre">	</span>Class.forName("javalx.Person").getMethod("setName", String.class);
<span style="white-space:pre">	</span>String s=(String) method.invoke(p, "zhangsan");
<span style="white-space:pre">	</span>Method method1=Class.forName("javalx.Person").getMethod("getName", null);
<span style="white-space:pre">	</span>System.out.println(method1.invoke(p, null));*/

(5)获取所有的方法

<span style="white-space:pre">	</span>Person p=new Person();
<span style="white-space:pre">	</span>Method[] method=Class.forName("javalx.Person").getMethods();
<span style="white-space:pre">	</span>for(Method m:method)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>if(m.getName()=="show") 
<span style="white-space:pre">		</span>m.invoke(p, null);
<span style="white-space:pre">	</span>}

(6) 反射出传递的参数类型

<span style="white-space:pre">	</span>Method method = ReflectTest.class.getMethod("appleyVector",Vector.class);
<span style="white-space:pre">	</span>Type[] type = method.getGenericParameterTypes();
<span style="white-space:pre">	</span>for (Type ty : type) {
<span style="white-space:pre">		</span>System.out.println(ty);
<span style="white-space:pre">	</span>}

 (7)反射类的main方法:

 <span style="white-space:pre">	</span>Class class =Person.class;
 <span style="white-space:pre">	</span>Method method=clazz.getMethod(“main”,String[].class);
 <span style="white-space:pre">	</span>Method.invoke(null,newObject[]{new String[]{“ss”,”dd”}});

注意:这里的newObject[]{new String[]{“ss”,”dd”}}在运行是他会进行拆包,为了拆出的是数组,所以有打了一层包

6.数组的反射:

 相同类型的相同维数的数组字节码相同,得到的是同一份字节码。

 基本类型的数组不能转换成Object

如下例子: int[] a = new int[3];Object[] obj= a;这样是不成立的。

无法得到某个数组的具体类型,只能得到其中某个元素的类

例如:int a = new int[3];Object[] obj= new Object[]{“ABC”,1}    

    Obj[0].getClass().getName()得到的是java.lang.Str

  若通过b.getClass().getName(),结果是:[Ljava.lang.Object;

7.反射的作用:

反射可以实现框架:比如说我想要用Collection中的ArrayLIst类,但是过了一段时间我又想要用Collection中的HashSet类,这时我们就可以写一个小小的框架来完成,把你要的类写到配置文件中,当你想要改变的时候直接改配置文件就可以了而不用改代码。

如下代码:

public class ReflectDemo2 {
	public static void main(String[] args) throws Exception {
	InputStream in=
ReflectDemo2.class.getClassLoader().getResourceAsStream("day02/config.properties");
		Properties p=new Properties();
		p.load(in);
		in.close();
		String className=p.getProperty("className");
		Collection c=
(Collection) Class.forName(className).newInstance();
		ReflectPoint rp1=new ReflectPoint(2,2);
		ReflectPoint rp2=new ReflectPoint(3,3);
		ReflectPoint rp3=new ReflectPoint(4,4);
		c.add(rp1);
		c.add(rp2);
		c.add(rp3);
		System.out.println(c.size());
	}

}

二、JavaBean和内省 IntroSpector

    1.JavaBean是一种特殊的Java类,主要用于传递数据信息,其中的方法名称等,都符合特殊的规则。只要一个类中含get和set打头的方法,就可以将其当做JavaBean使用。当一个类被当做JavaBean使用时,JavaBean属性是根据方法名来进行推断的,根本看不到内部的成员。

 2.内省  JDK中提供了对JavaBean进行操作的API,这套API称为内省,若要自己通过getX的方式来访问私有x

  3.我们要对JavaBean进行操作的话要推断出它的成员。

    因为JavaBean中都是setX、getX方法,所以如果第一个单词时大写的我们就把大写的字母改成小写:例如:getName--àname

     如果第一个单词不是大写的就不用改了。

     如果都是大写的也不用改了。

//获取bean的所有属性
		BeanInfo info=Introspector.getBeanInfo(Person.class,Object.class);
	    PropertyDescriptor[] pr = info.getPropertyDescriptors();//拿到所有属性的描述器
	    for(PropertyDescriptor p:pr)
	    {
		System.out.println(p.getName());
	}
    //相当于set属性
        Person p=new Person();
PropertyDescriptor pd=new PropertyDescriptor("age",Person.class);
		Method method=pd.getWriteMethod();
		method.invoke(p,23);
		System.out.println( p.getAge());
       //相当于get属性
		Method method1= pd.getReadMethod();
		System.out.println(method1.invoke(p, null));

   由于这种方法比较麻烦:引入了BeanUtils

BeanUtils的好处:

1.提供的set或get方法中,传入的是字符串,返回的还是字符串,因为在浏览器中,用户输入到文本框的都是以字符串的形式发送至服务器上的,所以操作的都是字符串。
也就是说这个工具包的内部有自动将整数转换为字符串的操作。
  2.支持属性的级联操作,即支持属性链。如可以设置:人的脑袋上的眼镜的眼珠的颜色。这种级联属性的属性连如果自己用反射,那就很困难了,通过这个工具包就可以轻松调用。

eanUtils.setProperty(p, "name", "lisi");
System.out.println(BeanUtils.getProperty(p, "name"));//获得name属性的值
	   System.out.println(p.getName());
	   BeanUtils.setProperty(p, "date.time", 111);
System.out.println(BeanUtils.getProperty(p, "date.time"));//获得name属性的值

三、注解

1.概述:注解相当于一种标记,在程序中加了注解就等于为程序打上了某种标记
        标记可以加在包、类、字段、方法、方法参数,以及局部变量上等等。
       格式:@注解类名()。如果有属性,则在括号中加上属性名(可省略)和属性值。
   2.java中三种最基本的注解:
       @SuppressWarning(”deprecation”)--->用于提示编译时的警告 源程序
      @Deprecated--->是用于提示方法已过时 运行时

       假定之前的某个类升级了,其中的某个方法已经过时了,不能够将过时的方法删除,

@Override--->提示覆盖父类方法   源程序看的

可对自己类中的方法判断是否是正确的覆盖父类的方法
3.注释的应用
   1、定义格式:@interface 名称{statement}
   2、判断一个类中是否加注解了:用这个isAnnotationPresent();方法

例如:AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)

        3、注解的生命周期:Java源文件àclass文件-à内存中的字节码

4、获得这个注解:用getAnnotation()这个方法

       例如:ItcastAnnotation annotation = (ItcastAnnotation)AnnotationTest.class.getAnnotation(ItcastAnnotation.class);

5、定义一个注解:

           @ Retention(RetentionPolicy.RUNTIME)//表示让它在运行阶段有

           @Target(ElementType.METHOD,ElementType.TYPE)//表示把这个注解写到方法上,如果你想要在类上也可以,就写上ElementType.TYPE

public @interface ItcastAnnotation {
	           String color();
               String value();
               int[] ArrayAttr();//数组类型的
               EnumTest.TrafficLamp Lamp();default EnumTest. TrafficLamp.RDE//定义枚举类型的
               MetaAnnotation annotationAttr() default @MetaAnnotation("gdgfd");
               //定义一个注解类型的
}
//定义了一个注解
public @interface MetaAnnotation {
	String value();
}

 6、在我的程序中应用我自己定义好的注解

例如:       

@ ItcastAnnotation
(color=”red”,value=”dsf”,ArrayAttr={1,3,4}, annotationAttr=@MetaAnnotation("fdvgd"))//设置属性值
               public class AnnotationTest {
               public static void main(String[] args)
                {
                 
}
}

注意:如果只有一个value属性需要设置,可以省略value。例如:@ ItcastAnnotation(dsf);

如果你想要省略value,可以把color设置成default。例如:

String color();default red;

 注解相当于胸牌,属性实际上就是在胸牌上添加一些属性,比如说添加个颜色。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值