java 技术提升,复习,总结(二)
2014-01-06 09:20
513 查看
java 技术提升,复习,总结(二)
接上篇反射:
数组的反射,同样看代码理解:
4:ArrayList与HashSet
5:利用反射来处理javaBean
7:泛型的使用
接上篇反射:
数组的反射,同样看代码理解:
int [] a1 = new int[]{1,2,3}; int [] a2 = new int[4]; int[][] a3 = new int[2][3]; String [] a4 = new String[]{"a","b","c"}; System.out.println(a1.getClass() == a2.getClass()); System.out.println(a1.getClass() == a4.getClass()); System.out.println(a1.getClass() == a3.getClass()); System.out.println(a1.getClass().getName()); System.out.println(a1.getClass().getSuperclass().getName()); System.out.println(a4.getClass().getSuperclass().getName()); Object aObj1 = a1; Object aObj2 = a4; //Object[] aObj3 = a1; Object[] aObj4 = a3; Object[] aObj5 = a4; System.out.println(a1); System.out.println(a4); System.out.println(Arrays.asList(a1)); System.out.println(Arrays.asList(a4)); printObject(a4); printObject("xyz");
private static void printObject(Object obj) { Class clazz = obj.getClass(); if(clazz.isArray()){ int len = Array.getLength(obj); for(int i=0;i<len;i++){ System.out.println(Array.get(obj, i)); } }else{ System.out.println(obj); } }
4:ArrayList与HashSet
Collection collections = new HashSet(); ReflectPoint pt1 = new ReflectPoint(3,3); ReflectPoint pt2 = new ReflectPoint(5,5); ReflectPoint pt3 = new ReflectPoint(3,3); collections.add(pt1); collections.add(pt2); collections.add(pt3); collections.add(pt1);
System.out.println(collections.size());
public class ReflectPoint { private int x; public int y;
public ReflectPoint(int x, int y) { super(); this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ReflectPoint other = (ReflectPoint) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } }
5:利用反射来处理javaBean
ReflectPoint pt1 = new ReflectPoint(3,5); String propertyName = "x";
Object retVal = getProperty(pt1, propertyName); System.out.println(retVal); Object value = 7; setProperties(pt1, propertyName, value);
private static void setProperties(Object pt1, String propertyName, Object value) throws IntrospectionException, IllegalAccessException, InvocationTargetException { PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass()); Method methodSetX = pd2.getWriteMethod(); methodSetX.invoke(pt1,value); } private static Object getProperty(Object pt1, String propertyName) throws IntrospectionException, IllegalAccessException, InvocationTargetException { /*PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass()); Method methodGetX = pd.getReadMethod(); Object retVal = methodGetX.invoke(pt1);*/ BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass()); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); Object retVal = null; for(PropertyDescriptor pd : pds){ if(pd.getName().equals(propertyName)) { Method methodGetX = pd.getReadMethod(); retVal = methodGetX.invoke(pt1); break; } } return retVal; }
使用第三方的BeanUtils工具类对javaBean进行操作 方法一: //获取变量值 pt1 为javaBean对象 System.out.println(BeanUtils.getProperty(pt1, "x")); //给变量设值 BeanUtils.setProperty(pt1, "x", "9"); System.out.println(pt1.getX()); 方法二: /* //java7的新特性 Map map = {name:"zxx",age:18}; //将map对象转成javaBean类型 BeanUtils.setProperty(map, "name", "lhm"); */ //birthday.time 找到属性 BeanUtils.setProperty(pt1, "birthday.time", "111"); System.out.println(BeanUtils.getProperty(pt1, "birthday.time")); PropertyUtils.setProperty(pt1, "x", 9); System.out.println(PropertyUtils.getProperty(pt1, "x"));
</pre><pre code_snippet_id="143817" snippet_file_name="blog_20140106_11_138342" name="code" class="java">******************************************
<span style="font-size:24px;">6 注解:</span> import java.lang.reflect.Method; import javax.jws.soap.InitParam; //使用注解 并为各个属性赋值 @ItcastAnnotation(annotationAttr=@MetaAnnotation("flx"),color="red",value="abc",arrayAttr={1}) public class AnnotationTest { /** * @param args */ @SuppressWarnings("deprecation") //过时警告 //使用带属性的注解,只有value属性时可直接赋值 @ItcastAnnotation("xyz") public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub System.runFinalizersOnExit(true); if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){ //检查是否使用了自定义的注解 ItcastAnnotation annotation = (ItcastAnnotation)AnnotationTest.class.getAnnotation(ItcastAnnotation.class); //调用注解的属性,获取属性值 System.out.println(annotation.color()); System.out.println(annotation.value()); System.out.println(annotation.arrayAttr().length); System.out.println(annotation.lamp().nextLamp().name()); //调用注解属性的值 System.out.println(annotation.annotationAttr().value()); } Method mainMethod = AnnotationTest.class.getMethod("main", String[].class); ItcastAnnotation annotation2 = (ItcastAnnotation)mainMethod.getAnnotation(ItcastAnnotation.class); System.out.println(annotation2.value()); } @Deprecated //将方法设置为过时 public static void sayHello(){ System.out.println("hi,传智播客"); } @override //对父类方法重写(覆盖) } import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import cn.itcast.day1.EnumTest; //元注解,该注解使得自定义的注解的生命周期最长 @Retention(RetentionPolicy.RUNTIME) //设置注解在方法和类(接口、枚举...)上使用 @Target({ElementType.METHOD,ElementType.TYPE}) /** *自定义注解 */ public @interface ItcastAnnotation { //定义注解的属性,默认属性为blue String color() default "blue"; //特殊的属性,使用时可直接赋值 String value(); //数组类型的属性 int[] arrayAttr() default {3,4,4}; //枚举类型的属性 EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED; //注解类型的属性 MetaAnnotation annotationAttr() default @MetaAnnotation("lhm"); } public @interface MetaAnnotation { String value(); }
7:泛型的使用
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub ArrayList collection1 = new ArrayList(); collection1.add(1); collection1.add(1L); collection1.add("abc"); //int i = (Integer)collection1.get(1); ArrayList<String> collection2 = new ArrayList<String>(); //collection2.add(1); //collection2.add(1L); collection2.add("abc"); String element = collection2.get(0); //new String(new StringBuffer("abc")); Constructor<String> constructor1 = String.class.getConstructor(StringBuffer.class); String str2 = constructor1.newInstance(/*"abc"*/new StringBuffer("abc")); System.out.println(str2.charAt(2)); //利用泛型通过反射向某一集合中添加不同类型的数据 ArrayList<Integer> collection3 = new ArrayList<Integer>(); //通过编译后的对象一样 System.out.println(collection3.getClass() == collection2.getClass());//true //collection3.add("abc"); //添加字符串 collection3.getClass().getMethod("add", Object.class).invoke(collection3, "abc"); System.out.println(collection3.get(0)); //使用?通配符 printCollection(collection3); //通配符的扩展 /** *限定上边界: * 正确:Vector<? extends Number> = new Vector<Integer>(); * 错误:Vector<? extends Number> = new Vector<String>(); *限定下边界 * 正确:Vector<? supter Integer> = new Vector<Number>(); * 错误:Vector<? supter Integer> = new Vector<Byte>(); */ //Class<Number> x = String.class.asSubclass(Number.class); Class<?> y; Class<String> x ;//Class.forName("java.lang.String");>>>?表示返回任意类型 //泛型Map的使用 HashMap<String,Integer> maps = new HashMap<String, Integer>(); maps.put("zxx", 28); maps.put("lhm", 35); maps.put("flx", 33); Set<Map.Entry<String,Integer>> entrySet = maps.entrySet(); for(Map.Entry<String, Integer> entry : entrySet){ System.out.println(entry.getKey() + ":" + entry.getValue()); } //返回参数交集类型 add(3,5); Number x1 = add(3.5,3); Object x2 = add(3,"abc"); //使用自定义的泛型方法 swap(new String[]{"abc","xyz","itcast"},1,2); //swap(new int[]{1,3,5,4,5},3,4);//只能是引用类型才可以作为泛型参数 Object obj = "abc"; String x3 = autoConvert(obj); //(返回)类型参数的类型推断 copy1(new Vector<String>(),new String[10]); copy2(new Date[10],new String[10]); //copy1(new Vector<Date>(),new String[10]); //定义泛型变量的运用 GenericDao<ReflectPoint> dao = new GenericDao<ReflectPoint>(); dao.add(new ReflectPoint(3,3)); //String s = dao.findById(1); //Vector<Date> v1 = new Vector<Date>();//通过方法(利用泛型)获取参数类型 //利用反射、获取泛型对象参数 Method applyMethod = GenericTest.class.getMethod("applyVector", Vector.class);//获取方法 Type[] types = applyMethod.getGenericParameterTypes();//获取所有参数 ParameterizedType pType = (ParameterizedType)types[0]; System.out.println(pType.getRawType());//得到原始类型 System.out.println(pType.getActualTypeArguments()[0]); } public static void applyVector(Vector<Date> v1){ } //将任意类型的数组填充为统一类型的对象 private static <T> void fillArray(T[] a,T obj){ for(int i=0;i<a.length;i++){ a[i] = obj; } } //自定义泛型方法,自动转换类型 private static <T> T autoConvert(Object obj){ return (T)obj; } //自定义泛型方法 private static <T> void swap(T[] a,int i,int j){ T tmp = a[i]; a[i] = a[j]; a[j] = tmp; } private static <T> T add(T x,T y){ return null; } //使用通配符 ?(应用变量) 这样可以传递 多种类型 public static void printCollection(Collection<?> collection){ //collection.add(1); //不能调用此的方法(与参数类型有关) //size() 方法与参数类型无关 ,可以使用 System.out.println(collection.size()); for(Object obj : collection){ System.out.println(obj); } } //打印任意类型的集合 public static <T> void printCollection2(Collection<T> collection){ //collection.add(1); System.out.println(collection.size()); for(Object obj : collection){ System.out.println(obj); } } //将任意类型的集合拷贝到某一特定的集合 public static <T> void copy1(Collection<T> dest,T[] src){ }
import java.util.Set; //定义泛型变量的运用(模拟数据库的操作) //dao data access object--->crud public class GenericDao<E> { public void add(E x){ } public E findById(int id){ return null; } public void delete(E obj){ } public void delete(int id){ } public void update(E obj){ } public static <E> void update2(E obj){ } public E findByUserName(String name){ return null; } public Set<E> findByConditions(String where){ return null; } }
相关文章推荐
- java十年技术栈[总结复习用]
- 对java技术提升的定级总结
- java十年技术栈[总结复习用]
- java核心技术复习笔记(二)
- 黑马程序员-----java中你必须掌握的线程技术一DAY15总结
- 黑马程序员---一DAY16总结--java中你必须掌握的集合框架技术
- java Web 分页技术总结
- java后端1年经验和技术总结(1)
- Java技术总结
- java xml技术简单总结
- java核心技术卷二文件输入输出总结
- Java后端1年经验和技术总结
- java基础技术知识点总结——static关键字
- Java复习总结——框架篇(三)
- Java连接池总结复习及推荐
- Java核心技术及面试指南 键值对方面的面试题总结以及答案
- JAVA之IO技术的操作总结
- 总结Java常用到的六个加密技术和代码
- Java I/o复习与总结 Dome 一
- JAVA通信系列一:Java Socket技术总结