//定义一个数组Object[] arr ={"1"};if(arr[0]instanceofString a){//假如我们只想判断值为String,取 String.class,那还是别定义 a 变量了。System.out.println("相同的取值:"+String.class+",a的class:"+ a.getClass());System.out.println(a);}//是不是 这样更简便呢?if(arr[0]instanceofString){//String.class 是我们想要的System.out.println(String.class);}
2. switch,遇到两个问题
java 17 Preview 增加了 switch的模式匹配,代码减少很多。
问题1:我并不用变量a,我还必须定义它,改怎么写呢?
Object[] arr ={"1"};switch(arr[0]){caseString a ->System.out.println("第一个分支:"+String.class+"值为:"+ a);default->System.out.println("默认:"+ arr[0].getClass());}//但是呢,我并不用变量a,我还必须定义它,否则会报错
问题2:如下代码,我该怎么优化呢?
Object[] arr ={newArrayList<>()};switch(arr[0]){caseArrayList a ->System.out.println("第二个分支:"+List.class);caseLinkedList a ->System.out.println("第二个分支:"+List.class);default->System.out.println("默认:"+ arr[0].getClass());}
3. 优化之后的两种方法
优化了之后,感觉 很 K猪
publicstaticClass<?>[]getClazzByArgsForJava16(Object[] args){Class<?>[] parameterTypes =newClass[args.length];for(int i =0; i < args.length; i++){if(args[i]instanceofString a){
parameterTypes[i]=String.class;continue;}//省略}return parameterTypes;}publicstatic<x>Class<?>[]getClazzByArgsForJava17Preview(Object[] args){Class<?>[] parameterTypes =newClass[args.length];for(int i =0; i < args.length; i++){switch(args[i]){caseArrayList a -> parameterTypes[i]=List.class;caseLinkedList a ->{
parameterTypes[i]=List.class;}caseHashMap a -> parameterTypes[i]=Map.class;caseLong a -> parameterTypes[i]=long.class;caseDouble a -> parameterTypes[i]=double.class;caseTimeUnit a -> parameterTypes[i]=TimeUnit.class;default-> parameterTypes[i]= args[i].getClass();}}return parameterTypes;}
4. 原方法:
publicstaticClass<?>[]getClazzByArgs(Object[] args){Class<?>[] parameterTypes =newClass[args.length];for(int i =0; i < args.length; i++){if(args[i]instanceofArrayList){
parameterTypes[i]=List.class;continue;}if(args[i]instanceofLinkedList){
parameterTypes[i]=List.class;continue;}if(args[i]instanceofHashMap){
parameterTypes[i]=Map.class;continue;}if(args[i]instanceofLong){
parameterTypes[i]=long.class;continue;}if(args[i]instanceofDouble){
parameterTypes[i]=double.class;continue;}if(args[i]instanceofTimeUnit){
parameterTypes[i]=TimeUnit.class;continue;}
parameterTypes[i]= args[i].getClass();}return parameterTypes;}