Sunday, November 28, 2010

Get Property using Reflection C# +Java

התבקשתי לכתוב ב java class מאוד גדול (שלא ניתן לחלק אותו)ולהפוך אותו ל xml, סיקרן אותי מאוד כיצד כותבים את אותו class גם ב c#:
יש לציין שניתן להפוך Class ל XML גם בצורה אחרת דרך XmlSerializer.
להלן הקוד ב C#:
//Class into XML
//Get the Properties of the Class and
//Create xml element
XElement xml_line = new XElement("je");
Type type = MyClass.GetType(); //Get the Type of your Class
PropertyInfo[] properties = type.GetProperties(); //Get the PropertyOnly
foreach (PropertyInfo property in properties)
{
//Add the property value and the name to the xml
xml_line.Add(new XAttribute(property.Name, property.GetValue(MyClass, null).ToString()));
}
להלן הקוד ב java:

try 
{
//Class c = Class.forName("Person");
Field heightField;
Class c = p.getClass();
Field m[] = c.getDeclaredFields();
for (int i = 0; i < m.length; i++)
{
System.out.println(m[i].get(p));
}
}
catch (Throwable e) 
{
System.err.println(e);
}

Read more: Uzi Drori's Blog