5. 枚举中放抽象方法,和带参的构造方法
*枚举中如何用抽象方法,照理说有抽象方法它自己也是枚举类哦,那它里面的对象怎么去实现
*这些抽象方法呢?
*/
publicclassEnumTest {
publicstaticvoidmain(String[] args)throwsInterruptedException {
TraficLamp traficLamp=TraficLamp.red;
System.out.println("当前灯是"+traficLamp+"请稍等....");
TraficLamp lamp=traficLamp.nextLamp();
System.out.println("....下一个这的灯是"+lamp);
}
publicenumTraficLamp{
//这种即表示调用父类有参的构造方法
red(200){
publicTraficLamp nextLamp() {
returnyellow;
}
},
green(100){
publicTraficLamp nextLamp() {
returnred;
}
},
yellow(10){
publicTraficLamp nextLamp() {
returnyellow;
}
};
publicabstractTraficLamp nextLamp();
privateintwaitTime;
privateTraficLamp(intwaitTime){
this.waitTime=waitTime;
}
}
}
6.反射一
//一.
//Class:是java中描述类这一类事物就是Class.
//Class类描述了哪些方面的信息呢?类的名字,类的访问属性
//类所属于包名,字段名的列表,方法名称的列表,等等...
//其常用的方法有:getInterfaces()..getMethods().getMethod().
//getName()...getPackage()..getConstructors(). Field getDeclaredField(String name)
//getResourceAsStream(String name) ..getTypeParameters() ..
//Class cls1=字节码1
//Class cls2=字节码2请解释什么又是字节码?读class二制文件到内在中,才能创建一个个的对象。
//也即通才字节码去复制一个个的对象。当程序中用到了很类如Person类,Date类,Math类等,那么内存中就应该有三份字节码。
//这时每一份字节码都是一个Class的实例对象。
//二.得到一个类的字节码有三种方式?
// 2.2. Class.forName()的作用?
//答:其作用就是加载字节码,加载字节码有两种:内存中无则类加载器加载,内存中有不用加载
//八大基本数据类型对应 的八大基本数据对象:其中void也有类型对象,,如何来测试?
publicstaticvoidmain(String[] args)throwsClassNotFoundException {
Classclass1=TestClass.class;
Classclass3=newTestClass().getClass();
Classclass2=Class.forName("com.lovo.reflect.TestClass");
System.out.println(class1);
System.out.println(class2);
System.out.println(class3);
//以上是三种得到类加载器的方式
//以下是测试八种数据类型及void类类型的方式
Classt1=boolean.class;
System.out.println(t1);
Classs1=String.class;
System.out.println(s1);
Classv1=void.class;
System.out.println(v1);
//请测试字节码文件在内存中只有一份吗?
String ss1="abc";
Classcc1=ss1.getClass();
Classcc2=String.class;
Classcc3=Class.forName("java.lang.String");
System.out.println(cc1==cc2);//true
System.out.println(cc2==cc3);//true
//基本数据类型的判断与测试
System.out.println(Integer.class==int.class);//false;
System.out.println(Integer.class.isPrimitive());//false,不是基本数据类型
System.out.println(int.class.isPrimitive());//true
System.out.println(Integer.class==Integer.TYPE);//false
System.out.println(int.class== Integer.TYPE);//true
//说明基本数据类型的包装类型的type属性可以使其变为基本数据类型
//用反射测试数据是不是基本数据类型
System.out.println(int[].class.isPrimitive());//false
//用反射判断一个对象是不是数组
System.out.println(int[].class.isArray());//true
}
7.//拿到Person类中所有的构造方法
Constructor[] constructors=Person.class.getConstructors();
for(inti=0;i
System.out.println(constructors[i]);
}
//得到带两个参数的方法
Constructorcon1=Person.class.getConstructor(String.class,int.class);
System.out.println(con1);
//利用反射给Person类new一个不带参的实例
Person p=Person.class.getConstructor().newInstance();
System.out.println(p);
//利用反射给Person类new一个不带两参的实例
Constructorcon2=Person.class.getConstructor(String.class,int.class);
Person P2=(Person)con2.newInstance(newString("张三"),newInteger(2));
System.out.println(P2);
//用反射给一个属性赋值,再将该属性拿出来
Person pp=newPerson("李四",11);
//这时属性name竟然是String类型的,如是是private那应该怎么做呢?
// Field fieldName=pp.getClass().getField("name");
//强行察看别人的数据
Field fieldName=Person.class.getDeclaredField("age");
fieldName.setAccessible(true);
System.out.println(fieldName.get(pp));
8. 注意访问类属性用到的set(obj,value)和field.get(obj)这两个方法哦!!
publicstaticvoidmain(String[] args)throwsSecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
//将Person类中的为String的属性值中带b的改为a,但是别人Person中不设为public就通不过
Person sPerson=newPerson();
System.out.println(sPerson);
changeChar(sPerson);
System.out.println(sPerson);
}
publicstaticvoidchangeChar(Object obj)throwsIllegalArgumentException, IllegalAccessException{
Field[] fields=obj.getClass().getDeclaredFields();
for(Field field:fields){
if(field.getType() == String.class){
field.setAccessible(true);
String oldStr=(String)field.get(obj);
System.out.println(oldStr);
String newStr=oldStr.replace('b','a');
field.set(obj, newStr);
}
}
9.//注意使用Class[]与Object[]。。。
publicstaticvoidmain(String[] args)throwsSecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class[] cls1=newClass[2];
cls1[0]=Integer.TYPE;
cls1[1]=Integer.TYPE;
Method method=Calculate.class.getMethod("add",cls1 );
Object object=method.invoke(new Calculate(), new Object[]{3,5});
Object[] arg=new Object[2];
arg[0]=3;
arg[1]=5;
Object object=method.invoke(newCalculate(), arg);
System.out.println((Integer)object);
}
10.Method charAtMethod = String.class.getMethod("charAt", Integer.TYPE);
Object object = charAtMethod.invoke(newjava.lang.String("fdsfdfg"), 5);
System.out.println(object);
11.
publicclassTestClass {
publicstaticvoidmain(String[] args)throwsSecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
// Test.main(new String[] { "daf", "dfjakl" });
// 为什么要用反射的方式调:
//我并不知道这个Test类,执行这个main方法的时候
//传了一些参数过来
String className=args[0];
Method method=Class.forName(className).getMethod("main", String[].class);
method.invoke(null,newObject[]{newString[]{"daf","dfjakl"}});
}
}
classTest {
publicstaticvoidmain(String[] args) {
for(String str : args) {
System.out.println(str);
}
}
}
12. 注意:java.lang.reflect.Array这个类的作用,它可以拿到一个数组的长度和得到数组中的元素的值
publicstaticvoidmain(String[] args)throwsSecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException,
ClassNotFoundException {
// 用反射得到一个数组的长度,得到数组的值,并改变数组的的值
// 你传一个Object我就把它给打印出来
Object object=newint[]{4,5,7,8,7} ;
chageObject(object);
}
privatestaticvoidchageObject(Object object) {
Classclass1 = object.getClass();
if(class1.isArray()) {
for(inti = 0; i
System.out.println(Array.get(object, i));
}
}else{
System.out.println(object);
}
}
13. publicclassReflectPoint {
privateintx;
publicinty;
publicStringstr1="ball";
publicStringstr2="basketball";
publicStringstr3="itcast";
publicReflectPoint(intx,inty) {
super();
this.x= x;
this.y= y;
}
// publicinthashCode() {
// finalintprime = 31;
// intresult = 1;
// result = prime * result + x;
// result = prime * result + y;
// return result;
// }
publicinthashCode() {
returnthis.x+this.y;
}
@Override
publicbooleanequals(Object obj) {
if(this== obj)
returntrue;
if(obj ==null)
returnfalse;
if(getClass() != obj.getClass())
returnfalse;
finalReflectPoint other = (ReflectPoint) obj;
if(x!= other.x)
returnfalse;
if(y!= other.y)
returnfalse;
returntrue;
}
publicstaticvoidmain(String[] args) {
// Collection collections=new ArrayList(); //打印共有4个
Collectioncollections =newHashSet();//重写了hashCode则只有2个,没重写就有3个
ReflectPoint p1 =newReflectPoint(2, 3);
ReflectPoint p2 =newReflectPoint(4, 4);
ReflectPoint p3 =newReflectPoint(2, 3);
collections.add(p1);
collections.add(p2);
collections.add(p3);
collections.add(p1);
p1.y=8;//重了hashCode.改了hashCode中的值则不能删除
collections.remove(p1);
System.out.println(collections.size());
//如查想查找一个集合中是否包含某个对象,大概的程序代码怎样写呢
//通常是逐一取出每个元素与要查找的对进行比较,当发现某个元素与要果找的】
//进行equlas()方法比较的结查相等时,则停止继续查找关返回肯定的信息
//否则,返回否定的信息,如果一个集合中有很多对象,一万个,有人发明了
//一种哈希算法来提高从集合中查找集合元素的效率,这种方式将集合分成
//若干个存储区域,每个对象可以计算出一个哈希码,可以将哈希分组,每组
//分别对应某个存储区域,根据一个对象的哈希码就可以确定该对象应该存储
//在应该存储大哪个区域.
//HashSet就是采用哈希算法存取对象的集合,它内部采用了某个数字n
//进行取余的方式对哈希码进行分组和划分对象的存储区域。Object对象
//定义了一个hashCode()方法来返回每个Java对象的哈希码,当从HashSet
//中找到某个对象时,Java系统首先调用对象的hashCode()方法获得对象的
//哈希码,然后根据哈希码找到相应的存储区域。最后取出该存储区域的
//每个元素与该对象进行equals方法比较,这样不遍历集合就可以得到结论。
}
14. properties文件下有:
className=java.util.ArrayList
publicstaticvoidmain(String[] args)throwsIOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
//InputStream iStream=new FileInputStream("src//properties//config.properties");
InputStream iStream= Test.class.getClassLoader().getResourceAsStream("cn//itcast//day1//config.properties");
InputStream iStream=newFileInputStream("src//properties//config.properties");
Properties properties=newProperties();
properties.load(iStream);
iStream.close();
String className=properties.getProperty("className");
Collectioncollections=(Collection)Class.forName(className).newInstance();
ReflectPoint p1 =newReflectPoint(2, 3);
ReflectPoint p2 =newReflectPoint(4, 4);
ReflectPoint p3 =newReflectPoint(2, 3);
collections.add(p1);
collections.add(p2);
collections.add(p3);
collections.add(p1);
p1.y=8;
//collections.remove(p1);
System.out.println(collections.size());
}
得到资源文件的方式,一定要得到完整的路径,那不是硬编码,而是运算出来的..getRealPath()...
//类加载器的作用就是把硬盘上的东西(.class)加载到内在中去。那它也能加载普通的文件到内存中哦。。
就应该放在包下面
15. PropertyDescriptor属性描述器的使用
publicstaticvoidsetProperties(Object obj, String propertyName,
String value)throwsIntrospectionException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
// PropertyDescriptor是属性文件的描述管理器
PropertyDescriptor pd =newPropertyDescriptor(propertyName, obj.getClass());
Method methodSetx = pd.getWriteMethod();
methodSetx.invoke(obj, value);
}
publicstaticObject getProperty(Object obj, String propertyName)throwsIntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd=newPropertyDescriptor(propertyName,obj.getClass());
Method methodGetX=pd.getReadMethod();
ObjectgetVal=methodGetX.invoke(obj);
returngetVal;
}
16. BeanInfo的使用….Introspector.getBeanInfo(obj.getClass());
publicstaticObject getProperty(Object obj, String propertyName)throwsIntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
//BeanInfo专门管理javaBean的一个类
BeanInfo beanInfo=Introspector.getBeanInfo(obj.getClass());
//拿到的所有的属性,注意只能拿到所有的属性哦
PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
Object getVal=null;
for(PropertyDescriptor pd:pds){
if(pd.getName().equals(propertyName)){
Method methodGetX=pd.getReadMethod();
getVal=methodGetX.invoke(obj);
}
}
returngetVal;
}
17.