MethodHandle基本用法

1 篇文章 0 订阅
1 篇文章 0 订阅
package org.suych;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class MethodHandleTest {

	private String name;

	// 构造方法
	public MethodHandleTest(String name) {
		this.name = name;
	}

	// 公共方法
	public String publicTest() {
		return name + "'publicTest";
	}

	// 静态方法
	public static String publicStaticTest() {
		return "'publicStaticTest";
	}

	// 私有方法
	private String test(int param) {
		switch (param) {
		case 1:
			return "suych1";
		case 2:
			return "suych2";
		case 3:
			return "suych3";
		default:
			return "suych4";
		}
	}

	// Get方法
	public String getName() {
		return name;
	}

	// Set方法
	public void setName(String name) {
		this.name = name;
	}

	public static void main(String[] args) throws Throwable {
		// 构造方法
		MethodType mtConstructor = MethodType.methodType(void.class, String.class);
		MethodHandle mhConstructor = MethodHandles.lookup().findConstructor(MethodHandleTest.class, mtConstructor);
		MethodHandleTest businessHandle = (MethodHandleTest) mhConstructor.invokeExact("suych");
		System.out.println(businessHandle.getName());

		// 公共方法
		MethodType mtPublic = MethodType.methodType(String.class);
		MethodHandle mhPublic = MethodHandles.lookup().findVirtual(MethodHandleTest.class, "publicTest", mtPublic);
		String resultPublic = (String) mhPublic.invokeExact(businessHandle);
		System.out.println(resultPublic);

		// 静态方法
		MethodType mtPublicStatic = MethodType.methodType(String.class);
		MethodHandle mhPublicStatic = MethodHandles.lookup().findStatic(MethodHandleTest.class, "publicStaticTest",
				mtPublicStatic);
		String resultPublicStatic = (String) mhPublicStatic.invokeExact();
		System.out.println(resultPublicStatic);

		// 私有方法
		MethodType mtPrivate = MethodType.methodType(String.class, int.class);
		MethodHandle mhPrivate = MethodHandles.lookup().findSpecial(MethodHandleTest.class, "test", mtPrivate,
				MethodHandleTest.class);
		String resultPrivate = (String) mhPrivate.invokeExact(businessHandle, 1);
		System.out.println(resultPrivate);

		// Set方法
		MethodHandle mhSet = MethodHandles.lookup().findSetter(MethodHandleTest.class, "name", String.class);
		mhSet.invokeExact(businessHandle, "A");
		System.out.println(businessHandle.name);

		// Get方法
		MethodHandle mhGet = MethodHandles.lookup().findGetter(MethodHandleTest.class, "name", String.class);
		String resultGet = (String) mhGet.invokeExact(businessHandle);
		System.out.println(resultGet);

	}
}

执行结果:

suych
suych'publicTest
'publicStaticTest
suych1
A
A


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值