Java 8 接口默认方法似乎没有声明属性
2022-09-03 08:03:32
在我的应用程序中,我遇到了一个问题,即当类中的 getter 仅在接口中缺省时(Java 8 功能),因此没有 Java Beans 属性。即,对于正常方法调用,它的工作方式与标准方法相同,但对于通过“属性”进行访问,它的行为突然不同...
下面是一个测试用例:
import java.beans.Introspector;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.apache.commons.beanutils.PropertyUtils;
public class test
{
public static void main (String[] arguments) throws Exception
{
// Normal language-level invocation, works fine.
System.out.println (new Bean1 ().getFoo ());
System.out.println (new Bean2 ().getFoo ());
// Printing Java Beans properties; Bean2 doesn't have 'foo' property...
System.out.println (Arrays.stream (Introspector.getBeanInfo (Bean1.class).getPropertyDescriptors ())
.map ((property) -> property.getName ())
.collect (Collectors.joining (", ")));
System.out.println (Arrays.stream (Introspector.getBeanInfo (Bean2.class).getPropertyDescriptors ())
.map ((property) -> property.getName ())
.collect (Collectors.joining (", ")));
// First call behaves as expected, second dies with exception.
System.out.println (PropertyUtils.getProperty (new Bean1 (), "foo"));
System.out.println (PropertyUtils.getProperty (new Bean2 (), "foo"));
}
public interface Foo
{
default String getFoo ()
{
return "default foo";
}
}
public static class Bean1 implements Foo
{
@Override
public String getFoo ()
{
return "special foo";
}
}
public static class Bean2 implements Foo
{ }
}
结果:
special foo
default foo
class, foo
class
special foo
Exception in thread "main" java.lang.NoSuchMethodException: Unknown property 'foo' on class 'class test$Bean2'
at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1257)
at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:808)
at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:884)
at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:464)
at test.main(test.java:21)
问题:我是做错了什么,还是Java中的一个错误?除了从不使用默认方法(对于 getters/setter)之外,是否有其他解决方法,以防您以后可能需要将它们作为“属性”进行访问?
我一直讨厌Java的“传统属性”,这些属性往往会因为你打错了喷嚏而破裂。