方法引用--给方法起别名
引用静态方法 类名:: static 方法名
-----利用已经存在大代码
引用对象方法 对象:: 方法名
引用特定类方法 类名称::方法名
引用构造方法 类名称:: new
在JDK1.8才能使用。
方法引用--给方法起别名
引用静态方法 类名:: static 方法名
-----利用已经存在大代码
引用对象方法 对象:: 方法名
引用特定类方法 类名称::方法名
引用构造方法 类名称:: new
在JDK1.8才能使用。
进行引用基本上都是针对引用类型完成的--》只有数组、类、接口具有引用的操作,现追加方法的引用也是别名的引用
1.引用静态方法:类名称::static方法名称
package t.com.util;
interface IUtil<P,R>{
public R transform(P p);
}
public class Test {
public static void main(String args[]) {
IUtil<Integer,String> iu=String :: valueOf;
String s=iu.transform(1000);
System.out.println(s.length());
}
}
2.引用某个对象的方法:实例化对象::普通方法名称
package t.com.util;
interface IUtil<R>{
public R transform();
}
public class Test {
public static void main(String args[]) {
IUtil<String> iu="Hello":: toUpperCase;
System.out.println(iu.transform());
}
}
3.引用某个特定类的方法:类名称::普通方法
interface IUtil<R,P>{
public R compare(P p1,P p2);
}
public class Test {
public static void main(String args[]) {
IUtil<Integer,String> iu=String:: compareTo;
System.out.println(iu.compare("H","h"));
}
}
4.引用构造方法:类名称::new。
class Person{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
interface IUtil<R,P,F>{
public R create(P p,F F);
}
public class Test {
public static void main(String args[]) {
IUtil<Person,String,Integer> iu=Person:: new;
System.out.println(iu.create("Marry",20));
}
}
方法引用 ::
例子:String :: valueof;//进行方法引用
图中的zhuanhuan方法相当于string里面的valueof方法,实际上就相当于方法取了别名
引用,本质就是别名,方法类型的引用
1 引用静态方法:类名称::static方法名称;
2引用某个对象的方法:实例化对象::普通方法
3引用某个特定类的方法:类名称::普通方法
4引用构造方法:类名称::new
将相当于提供别名;
引用某个对象的方法
interface IUtil<R>{
public R zhuanhuan();
}
public class TestDemo{
public static void main(String[] args){
IUtil<String> iu="hello"::toUpperCase;
System.out.println(iu.zhuanhuan());
}
}