下面列出了javax.persistence.Id#java.beans.PropertyDescriptor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Gets the Property Descriptors
*
* @return The propertyDescriptors value
*/
public PropertyDescriptor[] getPropertyDescriptors()
{
try
{
Vector descriptors = new Vector();
PropertyDescriptor descriptor = null;
return (PropertyDescriptor[]) descriptors.toArray(new PropertyDescriptor[descriptors.size()]);
}
catch (Exception e)
{
// do not ignore, bomb politely so use has chance to discover what went wrong...
// I know that this is suboptimal solution, but swallowing silently is
// even worse... Propose better solution!
e.printStackTrace();
}
return null;
}
public void test_MixedBooleanSimpleClass11() throws Exception {
BeanInfo info = Introspector
.getBeanInfo(MixedBooleanSimpleClass11.class);
Method setter = MixedBooleanSimpleClass11.class.getDeclaredMethod(
"setList", int.class, boolean.class);
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
if (propertyName.equals(pd.getName())) {
assertTrue(pd instanceof IndexedPropertyDescriptor);
assertNull(pd.getReadMethod());
assertNull(pd.getWriteMethod());
assertNull(((IndexedPropertyDescriptor) pd)
.getIndexedReadMethod());
assertEquals(setter, ((IndexedPropertyDescriptor) pd)
.getIndexedWriteMethod());
}
}
}
/**
* 获取bean的字段值
*/
@SuppressWarnings("unchecked")
public static <T> T getProperty(Object bean, String prop)
throws ReflectiveOperationException {
if (bean == null) {
return null;
}
if (bean instanceof Map<?, ?>) {
return (T) ((Map<?, ?>) bean).get(prop);
}
PropertyDescriptor desc = BeanUtils
.getPropertyDescriptor(bean.getClass(), prop);
if (desc == null) {
throw new NoSuchFieldException();
}
Method method = desc.getReadMethod();
if (method == null) {
throw new NoSuchMethodException();
}
return (T) method.invoke(bean);
}
private static void test(Class type) {
for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(type)) {
PropertyDescriptor pdCopy = create(pd);
if (pdCopy != null) {
// XXX - hack! The Introspector will set the bound property
// since it assumes that propertyChange event set descriptors
// infers that all the properties are bound
pdCopy.setBound(pd.isBound());
String name = pd.getName();
System.out.println(" - " + name);
if (!compare(pd, pdCopy))
throw new Error("property delegates are not equal");
if (!pd.equals(pdCopy))
throw new Error("equals() failed");
if (pd.hashCode() != pdCopy.hashCode())
throw new Error("hashCode() failed");
}
}
}
public static void main(String[] args) throws IntrospectionException {
if (!BeanUtils.findPropertyDescriptor(MyBean.class, "test").isBound()) {
throw new Error("a simple property is not bound");
}
if (!BeanUtils.findPropertyDescriptor(MyBean.class, "list").isBound()) {
throw new Error("a generic property is not bound");
}
if (!BeanUtils.findPropertyDescriptor(MyBean.class, "readOnly").isBound()) {
throw new Error("a read-only property is not bound");
}
PropertyDescriptor[] pds = Introspector.getBeanInfo(MyBean.class, BaseBean.class).getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (pd.getName().equals("test") && pd.isBound()) {
throw new Error("a simple property is bound without superclass");
}
}
}
/**
* Return the Class of the property if it can be determined.
* @param bean The bean containing the property.
* @param propName The name of the property.
* @return The class associated with the property or null.
*/
private static Class<?> getDefaultClass(final Object bean, final String propName)
{
try
{
final PropertyDescriptor desc =
BEAN_UTILS_BEAN.getPropertyUtils().getPropertyDescriptor(
bean, propName);
if (desc == null)
{
return null;
}
return desc.getPropertyType();
}
catch (final Exception ex)
{
return null;
}
}
private static boolean hasAtLeastOneBeanProperty(Class<?> clazz) {
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(clazz);
} catch (IntrospectionException e) {
return false;
}
for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) {
if (beanProp.getReadMethod() != null && beanProp.getWriteMethod() != null) {
return true;
}
}
return false;
}
private LocalArmeriaPortElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {
super(member, pd);
final LocalArmeriaPort localArmeriaPort = ae.getAnnotation(LocalArmeriaPort.class);
final SessionProtocol protocol = localArmeriaPort.value();
Server server = getServer();
if (server == null) {
server = beanFactory.getBean(Server.class);
serServer(server);
}
Integer port = portCache.get(protocol);
if (port == null) {
port = server.activeLocalPort(protocol);
portCache.put(protocol, port);
}
this.port = port;
}
/**
* Positive test for getPropertyDescriptors(). Each property name
* listed in {@code properties} should be returned exactly once.
*/
public void testGetDescriptors() {
final PropertyDescriptor[] pd =
PropertyUtils.getPropertyDescriptors(bean);
assertNotNull("Got descriptors", pd);
final int[] count = new int[properties.length];
for (final PropertyDescriptor element : pd) {
final String name = element.getName();
for (int j = 0; j < properties.length; j++) {
if (name.equals(properties[j])) {
count[j]++;
}
}
}
for (int j = 0; j < properties.length; j++) {
if (count[j] < 0) {
fail("Missing property " + properties[j]);
} else if (count[j] > 1) {
fail("Duplicate property " + properties[j]);
}
}
}
public <T> T decode(ByteBuf buf, Class<T> targetClass) {
T result = BeanUtils.newInstance(targetClass);
PropertyDescriptor[] pds = getPropertyDescriptor(targetClass);
for (PropertyDescriptor pd : pds) {
Method readMethod = pd.getReadMethod();
Property prop = readMethod.getDeclaredAnnotation(Property.class);
int length = getLength(result, prop);
if (!buf.isReadable(length))
break;
if (length == -1)
length = buf.readableBytes();
Object value = null;
try {
value = read(buf, prop, length, pd);
} catch (Exception e) {
e.printStackTrace();
}
BeanUtils.setValue(result, pd.getWriteMethod(), value);
}
return result;
}
/**
* Sets properties from the BeanInfo supplement on the
* introspected PropertyDescriptor
*/
private void setDocInfoProps(DocBeanInfo dbi, PropertyDescriptor pds) {
int beanflags = dbi.beanflags;
if ((beanflags & DocBeanInfo.BOUND) != 0)
pds.setBound(true);
if ((beanflags & DocBeanInfo.EXPERT) != 0)
pds.setExpert(true);
if ((beanflags & DocBeanInfo.CONSTRAINED) != 0)
pds.setConstrained(true);
if ((beanflags & DocBeanInfo.HIDDEN) !=0)
pds.setHidden(true);
if ((beanflags & DocBeanInfo.PREFERRED) !=0)
pds.setPreferred(true);
if (!(dbi.desc.equals("null"))){
pds.setShortDescription(dbi.desc);
}
if (!(dbi.displayname.equals("null"))){
pds.setDisplayName(dbi.displayname);
}
}
private static PropertyDescriptor create(PropertyDescriptor pd) {
try {
if (pd instanceof IndexedPropertyDescriptor) {
IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
return new IndexedPropertyDescriptor(
ipd.getName(),
ipd.getReadMethod(),
ipd.getWriteMethod(),
ipd.getIndexedReadMethod(),
ipd.getIndexedWriteMethod());
} else {
return new PropertyDescriptor(
pd.getName(),
pd.getReadMethod(),
pd.getWriteMethod());
}
}
catch (IntrospectionException exception) {
exception.printStackTrace();
return null;
}
}
public void test_MixedSimpleClass30() throws Exception {
BeanInfo info = Introspector.getBeanInfo(MixedSimpleClass30.class);
Method indexedGetter = MixedSimpleClass30.class.getDeclaredMethod(
"getList", int.class);
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
if (propertyName.equals(pd.getName())) {
assertTrue(pd instanceof IndexedPropertyDescriptor);
assertNull(pd.getReadMethod());
assertNull(pd.getWriteMethod());
assertEquals(indexedGetter, ((IndexedPropertyDescriptor) pd)
.getIndexedReadMethod());
assertNull(((IndexedPropertyDescriptor) pd)
.getIndexedWriteMethod());
}
}
}
public static Map<String, Object> transBeanToMap(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<>();
try {
PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(obj);
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
protected void copyArray(SimpleBeanCopier beanCopier, BeanWrapper targetBeanWrapper, Class<?> propertyType, Cloneable cloneable, PropertyDescriptor toProperty, Object srcValue){
Assert.isTrue(propertyType==srcValue.getClass(), "property type is not equals srcValue type");
int length = Array.getLength(srcValue);
Object array = Array.newInstance(propertyType.getComponentType(), length);
if(isContainerValueCopyValueOrRef(cloneable, srcValue)){
for (int i = 0; i < length; i++) {
Array.set(array, i, Array.get(srcValue, i));
}
}else{
for (int i = 0; i < length; i++) {
// Object targetElement = newBeanCopier(propertyType.getComponentType()).fromObject(Array.get(array, i));
Object targetElement = beanCopier.fromObject(Array.get(array, i), propertyType.getComponentType());
Array.set(array, i, targetElement);
}
}
// targetBeanWrapper.setPropertyValue(toProperty.getName(), array);
setPropertyValue0(targetBeanWrapper, toProperty.getName(), array);
}
public static void transMap2Bean(Map<String, Object> map, Object obj) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (map.containsKey(key)) {
Object value = map.get(key);
// 得到property对应的setter方法
Method setter = property.getWriteMethod();
setter.invoke(obj, value);
}
}
} catch (Exception e) {
System.out.println("transMap2Bean Error " + e);
}
return;
}
/**
* Utility method which can take one payment and distribute its amount by ratio to the target payments
*
* @param source Source Payment
* @param targets Target Payment
* @param ratios Ratio to be applied for each target
*/
private void applyRatioToPaymentAmounts(AssetPayment source, AssetPayment[] targets, double[] ratios) {
try {
for (PropertyDescriptor propertyDescriptor : assetPaymentProperties) {
Method readMethod = propertyDescriptor.getReadMethod();
if (readMethod != null && propertyDescriptor.getPropertyType() != null && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
KualiDecimal amount = (KualiDecimal) readMethod.invoke(source);
if (amount != null && amount.isNonZero()) {
KualiDecimal[] ratioAmounts = KualiDecimalUtils.allocateByRatio(amount, ratios);
Method writeMethod = propertyDescriptor.getWriteMethod();
if (writeMethod != null) {
for (int i = 0; i < ratioAmounts.length; i++) {
writeMethod.invoke(targets[i], ratioAmounts[i]);
}
}
}
}
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public void test_MixedBooleanExtendClass12() throws Exception {
BeanInfo info = Introspector
.getBeanInfo(MixedBooleanExtendClass12.class);
Method getter = MixedBooleanSimpleClass41.class
.getDeclaredMethod("getList");
Method setter = MixedBooleanSimpleClass41.class.getDeclaredMethod(
"setList", boolean.class);
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
if (propertyName.equals(pd.getName())) {
assertFalse(pd instanceof IndexedPropertyDescriptor);
assertEquals(getter, pd.getReadMethod());
assertEquals(setter, pd.getWriteMethod());
}
}
}
/**
* Creates a description for the attribute corresponding to this property
* descriptor. Attempts to create the description using metadata from either
* the getter or setter attributes, otherwise uses the property name.
*/
@Override
protected String getAttributeDescription(PropertyDescriptor propertyDescriptor, String beanKey) {
Method readMethod = propertyDescriptor.getReadMethod();
Method writeMethod = propertyDescriptor.getWriteMethod();
ManagedAttribute getter =
(readMethod != null ? this.attributeSource.getManagedAttribute(readMethod) : null);
ManagedAttribute setter =
(writeMethod != null ? this.attributeSource.getManagedAttribute(writeMethod) : null);
if (getter != null && StringUtils.hasText(getter.getDescription())) {
return getter.getDescription();
}
else if (setter != null && StringUtils.hasText(setter.getDescription())) {
return setter.getDescription();
}
ManagedMetric metric = (readMethod != null ? this.attributeSource.getManagedMetric(readMethod) : null);
if (metric != null && StringUtils.hasText(metric.getDescription())) {
return metric.getDescription();
}
return propertyDescriptor.getDisplayName();
}
static List<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
return Arrays.stream(propDescArr)
.filter(nulls(customer))
.map(PropertyDescriptor::getName)
.collect(Collectors.toList());
}
@Test(expected = NullPointerException.class)
//@Test
public void testGetValueError() throws IntrospectionException{
PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(StoreLocatorErrorProperty.class);
//---------------------------------------------------------------
for (PropertyDescriptor propertyDescriptor : propertyDescriptors){
PropertyValueObtainer.getValue(new StoreLocatorErrorProperty(), propertyDescriptor);
}
}
public static void main(String[] args) throws Exception {
long time = System.nanoTime();
for (int i = 0; i < 1000; i++) {
new PropertyDescriptor("name", PropertyDescriptor.class);
new PropertyDescriptor("value", Concrete.class);
}
time -= System.nanoTime();
System.out.println("Time (ms): " + (-time / 1000000));
}
public static SqlParameterSource generateParameterMap(Object t, List<String> ignores){
Map<String, Object> paramMap = new HashMap<String, Object>();
ReflectHelper reflectHelper = new ReflectHelper(t);
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(t.getClass());
for (PropertyDescriptor pd : pds) {
if(null != ignores && ignores.contains(pd.getName())){
continue;
}
paramMap.put(pd.getName(), reflectHelper.getMethodValue(pd.getName()));
}
MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(paramMap);
return sqlParameterSource;
}
public static void main(String[] args) {
PropertyDescriptor[] array = BeanUtils.getPropertyDescriptors(SimpleBean.class);
for (PropertyDescriptor pd : array) {
BeanUtils.reportPropertyDescriptor(pd);
}
if (array.length != 3)
throw new Error("unexpected count of properties: " + array.length);
}
private static void test(Class type) {
PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, "prop");
if (pd instanceof IndexedPropertyDescriptor) {
error(pd, type.getSimpleName() + ".prop should not be an indexed property");
}
if (!pd.getPropertyType().equals(Color.class)) {
error(pd, type.getSimpleName() + ".prop type should be a Color");
}
if (null == pd.getReadMethod()) {
error(pd, type.getSimpleName() + ".prop should have classic read method");
}
if (null == pd.getWriteMethod()) {
error(pd, type.getSimpleName() + ".prop should have classic write method");
}
}
/**
* Returns an array of property descriptors for specified class.
*
* @param type the class to introspect
* @return an array of property descriptors
*/
public static PropertyDescriptor[] getPropertyDescriptors(Class type) {
try {
return Introspector.getBeanInfo(type).getPropertyDescriptors();
} catch (IntrospectionException exception) {
throw new Error("unexpected exception", exception);
}
}
private static Map<String, PropertyDescriptor> getpropmap(Class<?> clazz,
boolean incl_cls)
{
HashMap<String, PropertyDescriptor> propmap = null; // cache.get(clazz);
if (propmap == null)
{
try
{
BeanInfo bean_info = Introspector.getBeanInfo(clazz);
propmap = new HashMap<String, PropertyDescriptor>();
PropertyDescriptor beanprops[] = bean_info
.getPropertyDescriptors();
for (int i = 0; i < beanprops.length; i++)
{
// filter the Class property which is not used
if (!incl_cls && "class".equals(beanprops[i].getName()))
continue;
propmap.put(beanprops[i].getName(), beanprops[i]);
}
// cache.put(clazz, propmap);
} catch (IntrospectionException ex)
{
throw new HGException("The bean " + clazz.getName()
+ " doesn't want us to introspect it: " + ex.toString());
}
}
return propmap;
}
public static void copyProperties(Object target, Map source,boolean ignoreCase) {
Set<String> keys = source.keySet();
for(String key : keys) {
if ("xml:base".equalsIgnoreCase(key)){
continue;
}
PropertyDescriptor pd = getPropertyDescriptor(target.getClass(), key, ignoreCase);
if(pd == null) {
throw new IllegalArgumentException("not found property:'"+key+"' on class:"+target.getClass());
}
setProperty(target, pd, source.get(key));
}
}
private static Dimension[] findDimensions(TestClass testClass)
throws Throwable
{
List<FrameworkField> fields =
testClass.getAnnotatedFields(Inject.class);
if (fields.isEmpty())
{
throw new Exception("No fields of " + testClass.getName()
+ " have the @Inject annotation");
}
BeanInfo beanInfo = Introspector.getBeanInfo(testClass.getJavaClass());
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
Dimension[] dimensions = new Dimension[fields.size()];
int i = 0;
for (FrameworkField field : fields)
{
int modifiers = field.getField().getModifiers();
if (! Modifier.isPublic(modifiers) || ! Modifier.isStatic(modifiers))
{
throw new Exception("@Inject " + testClass.getName() + '.'
+ field.getField().getName()
+ " must be public static");
}
Dimension dim = new Dimension();
dim.property = field.getField().getAnnotation(Inject.class).value();
dim.descriptor = findDescriptor(testClass, descriptors, field, dim.property);
dim.values = (Object[]) field.get(null);
dimensions[i++] = dim;
}
return dimensions;
}
private static void test(Class type) {
PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, "prop");
if (pd instanceof IndexedPropertyDescriptor) {
error(pd, type.getSimpleName() + ".prop should not be an indexed property");
}
if (!pd.getPropertyType().equals(Color.class)) {
error(pd, type.getSimpleName() + ".prop type should be a Color");
}
if (null == pd.getReadMethod()) {
error(pd, type.getSimpleName() + ".prop should have classic read method");
}
if (null == pd.getWriteMethod()) {
error(pd, type.getSimpleName() + ".prop should have classic write method");
}
}