包含propertydescriptor类的词条

http://www.itjxue.com  2023-03-07 19:45  来源:未知  点击次数: 

类包含同类对象的属性名

类包含同类对象的属性名:使用BeanCopier,BeanCopier是属于cglib包里的API。

struct Test2{Test1 test1 ;Test2(Test1 t1):test1(t1){}}使用同样的调用代码,输出结果如下:Construct Test1Copy constructor for Test1。

import java.beans.BeanInfo。

import java.beans.IntrospectionException。

import java.beans.Introspector。

import java.beans.PropertyDescriptor。

类结构体异同:

C++增加了class类型后,仍保留了结构体类型(struct ),而且把它的功能也扩展了。C++允许用struct来定义一个类型。如可以将前面用关键字class声明的类类型改为用关键字struct。

为了使结构体类型也具有封装的特征,C++不是简单地继承C的结构体,而是使它也具有类的特点,以便于用于面向对象程序设计。

用struct声明的结构体类型实际上也就是类。用struct声明的类,如果对其成员不作private或public的声明,系统将其默认为public。

java内省和反射的区别

经过多方面的资料搜集整理,写下了这篇文章,本文主要讲解java的反射和内省机制,希望对大家有点帮助,也希望大家提出不同的看法!

1).内省(Introspector)是 Java 语言对 Bean 类属性、事件的一种缺省处理方法。例如类 A 中有属性 name, 那我们可以通过 getName,setName 来得到其值或者设置新的值。通过 getName/setName 来访问 name 属性,这就是默认的规则。 Java 中提供了一套 API 用来访问某个属性的 getter/setter 方法,通过这些 API 可以使你不需要了解这个规则(但你最好还是要搞清楚),这些 API 存放于包 java.beans 中。

2).直接通过属性的描述器java.beans.PropertyDescriptor类,来访问属性的getter/setter 方法;

相关代码:

public class Point {

private Integer x;

private Integer y;

public Point(Integer x, Integer y) {

super();

this.x = x;

this.y = y;

}

public Integer getX() {

return x;

}

public void setX(Integer x) {

this.x = x;

}

public Integer getY() {

return y;

}

public void setY(Integer y) {

this.y = y;

}

}

import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;

public class Reflect {

public static void main(String[] args) throws Exception {

Point point = new Point(2, 5);

String proName = "x";

getProperty(point, proName);

setProperty(point, proName);

}

private static void setProperty(Point point, String proName) throws Exception {

PropertyDescriptor proDescriptor = new PropertyDescriptor(proName, Point.class);

Method methodSetX = proDescriptor.getWriteMethod();

methodSetX.invoke(point, 8);

System.out.println(point.getX());// 8

}

private static void getProperty(Point point, String proName) throws Exception {

PropertyDescriptor proDescriptor = new PropertyDescriptor(proName, Point.class);

Method methodGetX = proDescriptor.getReadMethod();

Object objx = methodGetX.invoke(point);

System.out.println(objx);// 2

}

}

3).通过类 Introspector 来获取某个对象的 BeanInfo 信息,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后我们就可以通过反射机制来调用这些方法。

相关代码:

把2中的getProperty()修改成如下形式:

private static void getProperty(Point point, String proName) throws Exception {

BeanInfo beanInfo = Introspector.getBeanInfo(point.getClass());

PropertyDescriptor[] proDescriptors = beanInfo.getPropertyDescriptors();

for(PropertyDescriptor prop: proDescriptors){

if(prop.getName().equals(proName)){

Method methodGetx = prop.getReadMethod();

System.out.println(methodGetx.invoke(point));//8

break;

}

}

}

4).我们又通常把javabean的实例对象称之为值对象(Value Object),因为这些bean中通常只有一些信息字段和存储方法,没有功能性方法。一个JavaBean类可以不当JavaBean用,而当成普通类用。JavaBean实际就是一种规范,当一个类满足这个规范,这个类就能被其它特定的类调用。一个类被当作javaBean使用时,JavaBean的属性是根据方法名推断出来的,它根本看不到java类内部的成员变量(javabean的成员变量通常都是私有private的)。

5).除了反射用到的类需要引入外,内省需要引入的类如下所示,它们都属于java.beans包中的类,自己写程序的时候也不能忘了引入相应的包或者类。

import java.beans.BeanInfo;

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

6).下面讲解一些开源的工具类Beanutils,需要额外下载的,commons-beanutils.jar,要使用它还必须导入commons-logging.jar包,不然会出异常;

相关代码一:

public static void main(String[] args) throws Exception {

Point point = new Point(2, 5);

String proName = "x";

BeanUtils.setProperty(point, proName, "8");

System.out.println(point.getX());// 8

System.out.println(BeanUtils.getProperty(point, proName));// 8

System.out.println(BeanUtils.getProperty(point, proName).getClass().getName());// java.lang.String

BeanUtils.setProperty(point, proName, 8);

System.out.println(BeanUtils.getProperty(point, proName).getClass().getName());// java.lang.String

}

//我们看到虽然属性x的类型是Integer,但是我们设置的时候无论是Integer还是String,BeanUtils的内部都是当成String来处理的。

相关代码二:

BeanUtils支持javabean属性的级联操作;

public static void main(String[] args) throws Exception {

Point point = new Point(2, 5);//在point中加一个属性 private Date birth = new Date();并产生setter/getter方法

String proName = "birth";

Date date= new Date();

date.setTime(10000);

BeanUtils.setProperty(point, proName, date);

System.out.println(BeanUtils.getProperty(point, proName));

BeanUtils.setProperty(point, "birth.time", 10000);

System.out.println(BeanUtils.getProperty(point, "birth.time"));//10000

}

//之所以可以 BeanUtils.setProperty(point, "birth.time", 10000);这样写,那是因为Date类中有getTime()和setTime()方法,即Date类中相当于有time这个属性。

相关代码三:

BeanUtils和PropertyUtils对比:

public static void main(String[] args) throws Exception {

Point point = new Point(2, 5);

String proName = "x";

BeanUtils.setProperty(point, proName, "8");

System.out.println(BeanUtils.getProperty(point, proName));//8

System.out.println(BeanUtils.getProperty(point, proName).getClass().getName());//java.lang.String

// PropertyUtils.setProperty(point, proName, "8");//exception:argument type mismatch

PropertyUtils.setProperty(point, proName, 8);

System.out.println(PropertyUtils.getProperty(point, proName));//8

System.out.println(PropertyUtils.getProperty(point, proName).getClass().getName());//java.lang.Integer

}

//BeanUtils它以字符串的形式对javabean进行转换,而PropertyUtils是以原本的类型对javabean进行操作。如果类型不对,就会有argument type mismatch异常。

6).理解了相应的原理,那些现成的工具用起来就会更舒服,如Beanutils与PropertyUtils工具。这两个工具设置属性的时候一个主要区别是PropertyUtils.getPropety方法获得的属性值的类型为该属性本来的类型,而BeanUtils.getProperty则是将该属性的值转换成字符串后才返回。

总结

Web 开发框架 Struts 中的 FormBean 就是通过内省机制来将表单中的数据映射到类的属性上,因此要求 FormBean 的每个属性要有 getter/setter 方法。但也并不总是这样,什么意思呢?就是说对一个 Bean 类来讲,我可以没有属性,但是只要有 getter/setter 方法中的其中一个,那么 Java 的内省机制就会认为存在一个属性,比如类中有方法 setMobile ,那么就认为存在一个 mobile 的属性。

将 Java 的反射以及内省应用到程序设计中去可以大大的提供程序的智能化和可扩展性。有很多项目都是采取这两种技术来实现其核心功能,例如我们前面提到的 Struts ,还有用于处理 XML 文件的 Digester 项目,其实应该说几乎所有的项目都或多或少的采用这两种技术。在实际应用过程中二者要相互结合方能发挥真正的智能化以及高度可扩展性。

propertyGrid自定义排序以及[...]按钮的实现等

我明白你的第一个问题,但是后两个不好意思没明白

第一个问题是这样

//

// 摘要:

// 使用该集合的默认排序(通常为字母顺序)对集合中的成员进行排序。

public virtual PropertyDescriptorCollection Sort();

//

// 摘要:

// 使用指定的 System.Collections.IComparer 对此集合中的成员排序。

public virtual PropertyDescriptorCollection Sort(IComparer comparer);

//

// 摘要:

// 对此集合中的成员排序。首先应用指定的顺序,然后应用此集合的默认排序,后者通常为字母顺序。

public virtual PropertyDescriptorCollection Sort(string[] names);

//

// 摘要:

// 对此集合中的成员排序。首先应用指定的顺序,然后使用指定的 System.Collections.IComparer 进行排序。

public virtual PropertyDescriptorCollection Sort(string[] names, IComparer comparer);

/// summary

/// 返回此类型说明符所表示的对象的已筛选属性描述符的集合。

/// /summary

/// param name="attributes"用作筛选器的属性数组。它可以是 null。/param

/// returns

/// 一个 see cref="T:System.ComponentModel.PropertyDescriptorCollection"/see,包含此类型说明符所表示的对象的属性说明。默认为 see cref="F:System.ComponentModel.PropertyDescriptorCollection.Empty"/see。

/// /returns

public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)

{

int i = 0;

//parameterList是外面传入的待显示数据。

PropertyDescriptor[] newProps = new PropertyDescriptor[parameterList.Count];

foreach (ConfigParameter parameter in parameterList)

{

//由ConfigParameter,你自己定义的类型,转成PropertyDescriptor类型:

newProps[i++] = new SystemOptionsPropertyDescriptor(parameter, true, attributes);

}

//取得了PropertyDescriptor[] newProps;现在可以对它排序,否则就按照newProps的原有顺序显示;

//1.直接返回

PropertyDescriptorCollection tmpPDC = new PropertyDescriptorCollection(newProps);

return tmpPDC;

//2.默认字母顺序

PropertyDescriptorCollection tmpPDC = new PropertyDescriptorCollection(newProps);

return tmpPDC.Sort();

//3.数组的顺序:sortName就是属性的顺序,内容就是各个属性名。

string[] sortName = new string[] { "a","b","c","d" };

return tmpPDC.Sort(sortName);

//4.comparer规则定义的排序方式

ParameterListComparer myComp = new ParameterListComparer();//ParameterListComparer : IComparer

return tmpPDC.Sort(myComp);

//5.先数组,后comparer

return tmpPDC.Sort(sortName,myComp);

//而我采用的是把数据传入之前就排序完毕的方法:即调用之前,把数据parameterList排好顺序,再 1.直接返回。

}

//对于数组排序方法,可以声明称一个事件,由外部传入属性的实现顺序:

public delegate string[] SortEventHandler();

public class CustomTypeDescriptorExtend : CustomTypeDescriptor

{

public SortEventHandler OnSort;

//......其它代码

public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)

{

string[] sortName = OnSort();

PropertyDescriptorCollection tmpPDC = TypeDescriptor.GetProperties(typeof(CustomTypeDescriptorExtend), attributes);

return tmpPDC.Sort(sortName);

}

}

//使用时:

public MyMethod()

{

CustomTypeDescriptorExtend s = new CustomTypeDescriptorExtend();

s.OnSort += new SortEventHandler(SetSortors);

PropertyGrid1.SelectedObject = s;

PropertyGrid1.PropertySort = PropertySort.Categorized;

}

public string[] SetSortors()

{

return new string[] { "B", "A", "C" };

}

当然这也不是我写的,给你个原始链接吧,呵呵

Spring 常用工具类

StringUtils:(Spring 4.0+工具类)

public static boolean hasLength(CharSequence str)

public static boolean isEmpty(Object str)

public static boolean hasText(String str)

public static String replace(String inString, String oldPattern, String newPattern)

public static String delete(String inString, String pattern)

public static String capitalize(String str) //首字母大写

public static String uncapitalize(String str) ?//首字母小写

public static String getFilename(String path) //文件路径截取文件名

public static String getFilenameExtension(String path) ?//文件路径截取后缀

ClassUtils:(Spring 4.0+工具类)

public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError

public static boolean isPresent(String className, ClassLoader classLoader)

public static Class getUserClass(Class clazz) ?//CGLIB代理类获取父类

public static String getShortName(String className)

public static String getShortNameAsProperty(Class clazz) ?//获取类名且首字母变小写

public static Method getMostSpecificMethod(Method method, Class targetClass) ?//如果这个方法是接口的方法,则获取实现类中实现的方法

ObjectUtils:

BeanUtils:(Spring 4.0+工具类)

public static T instantiate(Class clazz) throws BeanInstantiationException

public static PropertyDescriptor[] getPropertyDescriptors(Class clazz) throws BeansException

public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) throws BeansException

public static PropertyDescriptor findPropertyForMethod(Method method) throws BeansException

public static PropertyDescriptor findPropertyForMethod(Method method, Class clazz) throws BeansException

public static Class findPropertyType(String propertyName, Class... beanClasses)

public static boolean isSimpleProperty(Class clazz)

public static boolean isSimpleValueType(Class clazz)

public static void copyProperties(Object source, Object target)

public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException

AnnotatedElementUtils,

AnnotationUtils:(Spring 4.0+工具类)

public static Map getAnnotationAttributes(Annotation annotation)

public static Object getValue(Annotation annotation) ?//获取注解上的value()值

public static Object getValue(Annotation annotation, String attributeName)

public static Object getDefaultValue(Annotation annotation)

public static Object getDefaultValue(Annotation annotation, String attributeName) ?//获取注解上的属性默认值

AnnotationAttributes: (Spring 4.0+工具类)

public AnnotationAttributes(Class annotationType)

public AnnotationAttributes(Map map)

public Class annotationType()

public String getString(String attributeName)

public String[] getStringArray(String attributeName)

public boolean getBoolean(String attributeName)

public N getNumber(String attributeName)

public Class getClass(String attributeName)

public AnnotationAttributes getAnnotation(String attributeName)

BeanWrapperImpl: (Spring 4.0+工具类)

public BeanWrapperImpl(Object object)

public BeanWrapperImpl(Class clazz)

public final Object getWrappedInstance()

public final Class getWrappedClass()

public void setPropertyValue(String propertyName, Object value) throws BeansException

public Class getPropertyType(String propertyName) throws BeansException

public Object getPropertyValue(String propertyName)

public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) //是否自动创建属性实例

public void setPropertyValues(Map map) throws BeansException

FileUtils:

public static File getFile(File directory, String... names)

public static Collection listFiles( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) ?//获取目录下的文件

public static Iterator iterateFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) ?//遍历目录下的文件

public static Collection listFiles(File directory, String[] extensions, boolean recursive) ?//获取目录下的文件,可指定是否递归

public static void copyFileToDirectory(File srcFile, File destDir) throws IOException ?//拷贝文件到指定目录

public static void copyFile(File srcFile, File destFile) throws IOException

public static long copyFile(File input, OutputStream output)

public static void copyInputStreamToFile(InputStream source, File destination)

public static void deleteDirectory(File directory) ? //删除目录

public static void cleanDirectory(File directory) ?//清空目录下文件

public static String readFileToString(File file)

public static byte[] readFileToByteArray(File file)

public static List readLines(File file)

public static void writeStringToFile(File file, String data) throws IOException ? //将String覆盖File内的内容

public static void writeStringToFile(File file, String data, String encoding, boolean append) ? //将String追加到File内

public static void writeLines(File file, String encoding, Collection lines) throws IOException

public static void writeLines(File file, String encoding, Collection lines, boolean append)

public static void writeLines(File file, Collection lines) throws IOException

IOUtils:

public static byte[] toByteArray(InputStream input) throws IOException

public static byte[] toByteArray(Reader input) throws IOException

public static char[] toCharArray(InputStream is) throws IOException

public static String toString(InputStream input) throws IOException

public static String toString(Reader input) throws IOException

public static List readLines(InputStream input) throws IOException

public static List readLines(Reader input) throws IOException

public static InputStream toInputStream(String input)

public static void write(byte[] data, OutputStream output)

public static void write(String data, OutputStream output) throws IOException

public static void writeLines(Collection lines, String lineEnding, OutputStream output) throws IOException

public static int copy(InputStream input, OutputStream output)

public static int copy(Reader input, Writer output) throws IOException

public static int read(InputStream input, byte[] buffer) throws IOException

public static int read(Reader input, char[] buffer) throws IOException

Character:

public static boolean isLowerCase(char ch)

public static boolean isUpperCase(char ch)

public static boolean isDigit(char ch)

ReflectionUtils:(Spring 4.0+工具类)

public static void doWithLocalMethods(Class clazz, MethodCallback mc)

public static void doWithMethods(Class clazz, MethodCallback mc)

public static void doWithMethods(Class clazz, MethodCallback mc, MethodFilter mf)

public static void doWithLocalFields(Class clazz, FieldCallback fc)

public static void doWithFields(Class clazz, FieldCallback fc)

public static void doWithFields(Class clazz, FieldCallback fc, FieldFilter ff)

ResolvableType:(Spring 4.0+工具类)

public static ResolvableType forClass(Class clazz)

public static ResolvableType forInstance(Object instance)

public static ResolvableType forField(Field field)

public static ResolvableType forConstructorParameter(Constructor constructor, int parameterIndex)

public static ResolvableType forMethodReturnType(Method method)

public static ResolvableType forMethodParameter(Method method, int parameterIndex)

public ResolvableType asMap()

public ResolvableType asCollection()

public ResolvableType as(Class type)

public ResolvableType getGeneric(int... indexes) ? //Map getGeneric(0) = Integer, getGeneric(1, 0) = String

public Class resolveGeneric(int... indexes)

public Class resolve()

Assert: (Spring 4.0+工具类)

public static void state(boolean expression, String message)

public static void isTrue(boolean expression, String message)

public static void isNull(Object object, String message)

public static void notNull(Object object, String message)

public static void hasText(String text, String message)

public static void notEmpty(Object[] array, String message)

public static void notEmpty(Collection collection, String message)

public static void notEmpty(Map map, String message)

public static void isInstanceOf(Class type, Object obj, String message)

public static void isAssignable(Class superType, Class subType, String message)

Arrays:

public static void sort(T[] a, Comparator c)

public static void fill(Object[] a, Object val)

public static List asList(T... a)

public static T[] copyOf(T[] original, int newLength)

Collections:

public static void sort(List list, Comparator c)

public static void fill(List list, T obj)

public static void copy(List dest, List src)

public static Collection unmodifiableCollection(Collection c)

public static List unmodifiableList(List list)

public static Map unmodifiableMap(Map m)

public static List singletonList(T o)

public static boolean addAll(Collection c, T... elements)

CollectionUtils (Spring 4.0+工具类)

public static boolean isEmpty(Collection collection)

public static boolean isEmpty(Map map)

public static boolean containsInstance(Collection collection, Object element)

MethodIntrospector: (Spring 4.0+工具类)

public static Map selectMethods(Class targetType, final MetadataLookup metadataLookup)

public static Set selectMethods(Class targetType, final ReflectionUtils.MethodFilter methodFilter)

public static Method selectInvocableMethod(Method method, Class targetType)

PropertyDescriptor: (Spring 4.0+工具类)

public PropertyDescriptor(String propertyName, Class beanClass) throws IntrospectionException

public synchronized Class getPropertyType()

public synchronized Method getReadMethod()

public synchronized Method getWriteMethod()

PropertyDescriptor如何通过这个类取得其他类的属性??

public class PropertyDescriptor extends Feature Descriptor PropertyDescriptor 描述 Java Bean 通过一对存储器方法导出的一个属性。

构造方法摘要

PropertyDescriptor(String propertyName, Class? beanClass)

通过调用 getFoo 和 setFoo 存取方法,为符合标准 Java 约定的属性构造一个 PropertyDescriptor。

PropertyDescriptor(String propertyName, Class? beanClass, String readMethodName, String writeMethodName)

此构造方法带有一个简单属性的名称和用于读写属性的方法名称。

PropertyDescriptor(String propertyName, Method readMethod, Method writeMethod)

此构造方法带有某一简单属性的名称,以及用来读取和写入属性的 Method 对象。

(责任编辑:IT教学网)

更多

推荐Flash实例教程文章