java8通过lambda表达式获取属性名称

有时候需要获取对象的属性名称,但是又不想写死,就可以用lambda获取。

直接上代码

1.实现一个自定义的SFunction类

import java.io.Serializable;
import java.util.function.Function;

@FunctionalInterface
public interface SFunction<T, R> extends Function<T, R>, Serializable {
}

2.实现PropertyNameExtractor工具类

public class PropertyNameExtractor {
    private PropertyNameExtractor() {
    }

    // 获取属性名称的方法
    public static <T, R> String getPropertyName(SFunction<T, R> getter) {
        try {
            // 获取序列化的Lambda
            Method writeReplace = getter.getClass().getDeclaredMethod("writeReplace");
            writeReplace.setAccessible(true);
            SerializedLambda lambda = (SerializedLambda) writeReplace.invoke(getter);

            // 从方法名中解析出属性名
            String methodName = lambda.getImplMethodName();
            if (methodName.startsWith("get")) {
                methodName = methodName.substring(3); // 去掉 "get"
            } else if (methodName.startsWith("is")) {
                methodName = methodName.substring(2); // 去掉 "is"
            }
            // 将首字母小写以符合JavaBean规范
            return Character.toLowerCase(methodName.charAt(0)) + methodName.substring(1);
        } catch (Exception e) {
            throw new RuntimeException("Failed to extract property name from getter", e);
        }
    }

    public static void main(String[] args) {
        // 使用方法引用 User::getName 来获取属性名称
        String propertyName = PropertyNameExtractor.getPropertyName(UserDO::getName);

        System.out.println("Property name: " + propertyName); // 输出:Property name: name
    }
}

3.使用方法

 // 使用方法引用 User::getName 来获取属性名称
 String propertyName = PropertyNameExtractor.getPropertyName(UserDO::getName);
 

抱歉,我之前的回答有误。在Java中,无法直接使用Lambda表达式获取属性名称Lambda表达式主要用于函数式接口的实现,而不是用于获取属性名称。 如果你想要通过Lambda表达式获取属性名称,你可以使用Java 8引入的`java.beans.Introspector`和`java.beans.PropertyDescriptor`来实现。以下是一个示例代码: ```java import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; public class Main { public static void main(String[] args) { Person person = new Person("John"); String propertyName = getPropertyName(person, Person::getName); System.out.println(propertyName); // 输出 "name" } public static <T> String getPropertyName(T obj, PropertyAccessor<T> accessor) { try { PropertyDescriptor[] descriptors = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors(); for (PropertyDescriptor descriptor : descriptors) { if (accessor.get(obj).equals(descriptor.getReadMethod().invoke(obj))) { return descriptor.getName(); } } } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return null; } } @FunctionalInterface interface PropertyAccessor<T> { Object get(T obj); } class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return name; } } ``` 在上述示例中,我们定义了一个`getPropertyName()`方法,该方法接收一个对象和一个属性访问器(PropertyAccessor)作为参数。在`getPropertyName()`方法中,我们使用`Introspector.getBeanInfo()`方法获取对象的属性描述器(PropertyDescriptor),然后使用属性访问器获取属性的值。如果找到与属性值匹配的属性描述器,则返回该属性名称。 在主方法中,我们使用`Person::getName`作为属性访问器,通过Lambda表达式传递给`getPropertyName()`方法来获取name属性名称。 请注意需要导入`java.beans.Introspector`和`java.beans.PropertyDescriptor`,并且Lambda表达式传递给`getPropertyName()`方法的参数型应为`PropertyAccessor<T>`函数式接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值