您的位置:首页 > 编程语言 > Java开发

Java8新特性——方法和构造函数引用

2014-06-07 21:33 429 查看
今天是高考的日子,是大四师兄师姐答辩毕业的日子。一代又来,一代又去。好久没写博客,借此特殊日子整理一下前不久学java8新特性时写的代码,留下痕迹。(本博客的代码根据 java8新特性教程 学习整理,加上个人的理解而成,关于某个新特性的介绍代码里的注释已经阐述清楚,故不再写文字介绍,直接看代码吧!)

本篇介绍java8的新特性之一:方法和构造函数引用。

1. 先定义一个JavaBean以作测试用:

public class Person {  
    public String firstName;  
    public String lastName;  
  
    public Person() {}  
  
    public Person(String firstName, String lastName) {  
        this.firstName = firstName;  
        this.lastName = lastName;  
    }  
}
2. 定义一个功能性接口IConvert以作测试用:

/**
 * 功能性接口
 */
@FunctionalInterface
interface IConvert<F,T>{
	
	//将F类型转换成T类型
	T convert(F from);
	default void  intValue2(){
	}
	default void  intValue3(){
	}
}


3. 过关键字::来传递方法和构造函数的引用:

import org.junit.Test;

/**
 * 方法和构造函数引用
 * java8可以让你通过关键字::来传递方法和构造函数的引用。
 */
public class MethodQuote {
	
	//在使用静态方法引用的情况下可以被进一步的简化:
	@Test
	public void staticMethodQuote(){
		//IConvert<String, Integer> convertor = (from) -> ( Integer.parseInt(from));
		IConvert<String, Integer> convertor = Integer::parseInt;
		int converted = convertor.convert("123");
		System.err.println(converted); //123
	}
	
	//引用对象方法
	@Test
	public void quoteObjectMethod(){
		Something something  = new Something();
		IConvert<String, String> convertor = something::startWith;
		String start = convertor.convert("asdfsadfa");
		System.err.println(start);  // y
	}
	
	//引用构造函数
	@Test
	public void quoteConstructorMethod() {
		//不使用通常的手动实现工厂类,通过使用构造函数将所有的工作联合在一起
		//通过Person::new创建一个指向Person构造函数的引用。
		//java编译器自动的选择正确的构造函数来匹配PersonFactory.create的函数签名。
		PersonFactory<Person> factory = Person::new;
		Person p = factory.create("zhuge", "xx");
		System.err.println(p);
		
	}

}

class Something{
	String startWith(String s){
		 return String.valueOf(s.charAt(0));
	}	
}

 
@FunctionalInterface
interface PersonFactory<P extends Person>{
	P create(String firstName, String lastName);
}


详情请见这篇博客: java8新特性教程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: