函数式接口、反射 相关练习

1、函数式接口作为方法返回值:

package learn;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Test {
    public static void main(String[] args) {
        ArrayList<String> array=new ArrayList<>();
        array.add("cccc");
        array.add("aa");
        array.add("b");
        array.add("ddd");

        Collections.sort(array, getComparator());

        System.out.println(array);//[b, aa, ddd, cccc]
    }

    public static Comparator<String> getComparator() {
        return (s1,s2)->s1.length()-s2.length();
    }
}

2、常用函数式接口之Consumer:
StringBuilder中的toString:
public String toString​()返回表示此顺序中的数据的字符串。 新的String对象被分配和初始化以包含此对象当前表示的字符序列。 然后返回String 。 对此序列的后续更改不影响String的内容。

package learn;

import java.util.function.Consumer;
public class Test {
    public static void main(String[] args) {
        operatorString("林青霞",s -> System.out.println(s),s -> System.out.println(new StringBuilder(s).reverse().toString()));
        //林青霞
        //霞青林
    }

    private static void operatorString(String name,Consumer<String> c1,Consumer<String> c2) {
        c1.andThen(c2).accept(name);
    }
}
package learn;

import java.util.function.Consumer;

public class Test {
    public static void main(String[] args) {
        String[] strArray={"林青霞,30","张曼玉,35","王祖贤,33"};

        print(strArray,s-> System.out.print("姓名:"+s.split(",")[0]),
                s-> System.out.println(",年龄:"+Integer.parseInt(s.split(",")[1])));
        //姓名:林青霞,年龄:30
        //姓名:张曼玉,年龄:35
        //姓名:王祖贤,年龄:33
    }

    private static void print(String[] strArray,Consumer<String> c1,Consumer<String> c2) {
        for(String str:strArray){
            c1.andThen(c2).accept(str);
        }
    }
}

3、常用函数接口Predicate 练习:

package learn;

import java.util.ArrayList;
import java.util.function.Predicate;

public class Test {
    public static void main(String[] args) {
        String[] strArray={"林青霞,30","张曼玉,35","王祖贤,33","柳岩,34"};

        ArrayList<String> array=myFilter(strArray, s-> s.split(",")[0].length()>2,
                s-> Integer.parseInt(s.split(",")[1])>33);

        for(String str:array){
            System.out.println(str);
        }
        //张曼玉,35
    }

    private static ArrayList<String> myFilter(String[] strArray, Predicate<String> c1, Predicate<String> c2) {
        ArrayList<String> arr=new ArrayList<>();
        for(String str:strArray){
            if(c1.and(c2).test(str)){
                arr.add(str);
            }
        }
        return arr;
    }
}

4、常用接口之Function 练习:

package learn;

import java.util.function.Function;

public class Test {
    public static void main(String[] args) {
        String s="林青霞,30";

        convert(s,ss->s.split(",")[1],ss->Integer.parseInt(ss),i->i+70);
        //100
    }

    private static void convert(String s, Function<String,String> f1, Function<String,Integer> f2,Function<Integer,Integer> f3) {
        int x=f1.andThen(f2).andThen(f3).apply(s);
        System.out.println(x);
    }
}

5、Stream流综合练习:

package learn;

import java.util.ArrayList;
import java.util.stream.Stream;

public class Test {
    public static void main(String[] args) {
        ArrayList<String> array=new ArrayList<>();
        array.add("周润发");
        array.add("成龙");
        array.add("刘德华");
        array.add("周星驰");
        array.add("李连杰");

        ArrayList<String> array2=new ArrayList<>();
        array2.add("林心如");
        array2.add("张曼玉");
        array2.add("林青霞");
        array2.add("林志玲");

        Stream.concat(array.stream().filter(s -> s.length()==3).limit(3),
                array2.stream().filter(s->s.startsWith("林")).skip(1)).map(s->new Actor(s)).forEach(s ->
                System.out.println(s.getName()));//map(Actor::new)也可
        //周润发
        //刘德华
        //周星驰
        //林青霞
        //林志玲
       
    }
}

6、反射获取构造方法:
通过反射获取私有构造方法并创建对象

正常不可以通过私有构造方法创建对象,但反射中可以。

package learn;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException,
            InvocationTargetException, InstantiationException, IllegalAccessException {
        //获取Class对象
        Class<?> c = Class.forName("learn.Student");
        Constructor<?> cons= c.getDeclaredConstructor(String.class);
        cons.setAccessible(true);
        Object obj = cons.newInstance("林青霞");

        System.out.println(obj);//Student{name='林青霞', age=0, address='null'}

    }
}
package learn;

public class Student {
    private String name;//私有
    int age;//默认
    public String address;
    public Student(){

    }

    private Student(String name){
        this.name=name;
    }

    Student(String name,int age){
        this.name=name;
        this.age=age;
    }

    public Student(String name,int age,String address){
        this.name=name;
        this.age=age;
        this.address=address;
    }

    private void function(){
        System.out.println("function");
    }

    public void method1(){
        System.out.println("method");
    }

    public void method2(String s){
        System.out.println("method:"+s);
    }

    public String method3(String s,int i){
        return s+","+i;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

7、反射获取成员方法并使用 练习:

package learn;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException,
            InvocationTargetException, InstantiationException, IllegalAccessException {
        //获取Class对象
        Class<?> c = Class.forName("learn.Student");

        Constructor<?> cons = c.getConstructor();
        Object obj = cons.newInstance();//Student对象

        Method method1 = c.getMethod("method1");
        method1.invoke(obj);

        Method method2=c.getMethod("method2",String.class);
        method2.invoke(obj,"林青霞");

        Method method3=c.getMethod("method3", String.class, int.class);
        String s=(String) method3.invoke(obj,"林青霞",30);//强制类型转化 object->string
        System.out.println(s);

        Method method4=c.getDeclaredMethod("function");
        method4.setAccessible(true);
        method4.invoke(obj);
        //method
        //method:林青霞
        //林青霞,30
        //function
    }
}

8、运行配置文件中指定类的指定方法

package learn;

import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException, 
            NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

        FileReader fr=new FileReader("hh\\src\\class.txt");
        Properties p=new Properties();
        p.load(fr);
        fr.close();

        //获取Class对象
        Class<?> c = Class.forName(p.getProperty("className"));

        Constructor<?> cons = c.getConstructor();
        Object obj = cons.newInstance();//Student对象

        Method method = c.getMethod(p.getProperty("methodName"));
        method.invoke(obj);//method
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值