Java 中Function 的一种写法

今天再看zuul2 源代码是看到这种 Lambda 表达式的写法, 记录一下

private static final Map< Class, Function > PARSERS = new HashMap<>();

static {

	PARSERS.put( Boolean.class, Boolean::valueOf );

	PARSERS.put( Boolean.TYPE, Boolean::valueOf );

	PARSERS.put( Byte.class, Byte::valueOf );

	PARSERS.put( Byte.TYPE, Byte::valueOf );

	PARSERS.put( Short.class, Short::valueOf );

	PARSERS.put( Short.TYPE, Short::valueOf );

	PARSERS.put( Integer.class, Integer::valueOf );

	PARSERS.put( Integer.TYPE, Integer::valueOf );

	PARSERS.put( Long.class, Long::valueOf );

	PARSERS.put( Long.TYPE, Long::valueOf );

	PARSERS.put( Float.class, Float::valueOf );

	PARSERS.put( Float.TYPE, Float::valueOf );

	PARSERS.put( Double.class, Double::valueOf );

	PARSERS.put( Double.TYPE, Double::valueOf );

	PARSERS.put( Character.class, s -> s.charAt( 0 ) );

	PARSERS.put( Character.TYPE, s -> s.charAt( 0 ) );

	PARSERS.put( String.class, s -> s );

	PARSERS.put( Duration.class, Duration::parse );

	PARSERS.put( Period.class, Period::parse );

	PARSERS.put( Instant.class, Instant::parse );

	PARSERS.put( ZonedDateTime.class, ZonedDateTime::parse );

	PARSERS.put( ZoneId.class, ZoneId::of );

}

 

举个 例子吧

 

接口

public interface ZuulFilter {
// 只有一个方法, 其他方法要有默认的实现
	String filterName(String name);

	default int filterOrder() {
		return 0;
	}

}
 测试代码
public static void main(String[] args) {

	ZuulFilter filter = (name) -> {

		return name.toLowerCase();

	};

	filter.filterName( "JAY" );

	Map, Function> map = new HashMap, Function>();

	map.put( Boolean.class, Boolean::valueOf );
	map.put( Boolean.TYPE, Boolean::valueOf );

	// 相当于这种函数的写法
	map.put( Byte.class, (t) -> {

		return Byte.valueOf( t );

	} );
		
	map.put( Byte.TYPE, (t) -> {

		return Byte.valueOf(t);

	} );

	System.out.println( map.get( Boolean.class ).apply( "true" ) );
		
	System.out.println( map.get( Byte.class ).apply( "47" ) );

}
 

 复杂一些的Function 的写法

public static  T usingSystemProperties( Class cls, String prefix ) {

	return createProxy( cls, k -> System.getProperty( prefix + k ) );

}

 

@SuppressWarnings("unchecked")
public static  T createProxy( Class cls, Function props ) {

	final Class[] interfaces = new Class[] { cls };

//	java.lang.reflect.InvocationHandler
	return (T) Proxy.newProxyInstance( classLoader(), interfaces, ( proxy, method, args ) -> {

		final String name = method.getName();

		if ( method.isDefault() ) {

			return invokeDefault( proxy, method, args );

		} else if ( "get".equals( method.getName() ) ) {
		
			return props.apply( ( String ) args[ 0 ] );
		
		} else {

			Class rt = method.getReturnType();

			String v = props.apply( name );

			if ( v == null ) {

				throw new NoSuchElementException( "could not find value for config setting: " + name );

			}
	
			return valueOf( rt, v );

		}

	} );

}

 

 

 

你可能感兴趣的:(源代码学习)