How to get the value of an annotated variable? - variables

So, I'm writing a method that will get annotated variables (doubles) and store them in a map. The variables are elements of an object. The name of the variable should be the key and its value - the parameter.
public void putInMap() {
Field[] fields = this.getClass().getDeclaredFields();
for (Field v: fields) {
if (v.isAnnotationPresent(Annotation.class))
map.put(v.getName(), *value here* );
}
}
My question is how to get the value of the variable (which is now a Field) so that I could put it in my map?

Try:
for (Field v : fields) {
if (v.isAnnotationPresent(Annotation.class)) {
v.setAccessible(true);
map.put(v.getName(), v.get(this));
}
}

Related

how to deal with stored properties's set and get in swift

this is a way we deal with property in OC
- (void)setText:(NSString *)text
{
if ([text isEqualToString:#"ss"]) {
_text = #"xx";
return
}
_text = text;
}
- (NSString *)text
{
return _text;
}
this is a wrong way in swift, we can't call self.xx in set.
var text : NSString {
get {
return self.text
}
set {
if newValue.isEqualToString("ss") {
self.text = "xx"
} else {
self.text = newValue
}
}
}
My question is how to transfer the OC code to Swift code.
You're confusing stored properties with computed properties.
Only computed properties have a getter and an optional setter; stored properties don't have either. Also, the setter in a computed property isn't there to set the value of the computed property (it can't, as the property is, well, computed and does not have an independent existence); rather, it's used to set the values of other properties, whose values are used to compute the computed property when it's next accessed. See this post for an example of that.
Now, stored properties can have property observers. In your specific example, it would look like this:
var text : NSString! {
didSet {
if text.isEqualToString("ss" as NSString) {
text = "xx" as NSString
}
}
}
You can also have a willSet block. Note that in Swift 1.2 NSString and String are no longer automatically bridged so you need to cast them onto each other when necessary.
While I don't know much about using a getter and setter on a stored property, in your case you can just use a property observer didSet.
var text: String! {
didSet {
if text == "ss" {
text = "xx"
}
}
}
You can try this way!
var text: NSString = ""
var newText : NSString {
get {
return text
}
set {
if newValue.isEqualToString("ss") {
text = "xx"
} else {
text = newValue
}
}
}

Check for existing mapping when writing a custom applier in ConfORM

I am writing my first custom column name applier for ConfORM.
How do I check if another column has already been map with same mapping name?
This is what I have so far:
public class MyColumnNameApplier : IPatternApplier<PropertyPath, IPropertyMapper>
{
public bool Match(PropertyPath subject)
{
return (subject.LocalMember != null);
}
public void Apply(PropertyPath subject, IPropertyMapper applyTo)
{
string shortColumnName = ToOracleName(subject);
// How do I check if the short columnName already exists?
applyTo.Column(cm => cm.Name(shortColumnName));
}
private string ToOracleName(PropertyPath subject)
{
...
}
}
}
I need to shorten the generated column names to less than 30 characters to fit in with Oracle's 30 character limit. Because I am shortening the column names it is possible that the same column name can potentially be generated two different properties. I would like to know when a duplicate mapping occurs.
If I don't handle this scenario ConfORM/NHibernate allows two different properties to 'share' the same column name - this is obviously creates a problem for me.
if column names are mapped twice you will get exception about parameter count on first load. You can can check after configuring:
foreach (var clazz in config.ClassMappings)
{
var propertiesWithOneColumn = clazz.PropertyClosureIterator.Where(p => p.ColumnSpan == 1);
var distinctColumns = new HashSet<string>();
foreach (var prop in propertiesWithOneColumn)
{
var col = prop.ColumnIterator.First().Text;
if (distinctColumns.Add(col))
{
Console.WriteLine("duplicate column "+ col + " found for property " + prop.PersistentClass.ClassName + "." + prop.Name);
}
}
}

How to find the value of an attribute

How can I find the value of an attribute? I need to check the value and set the textbox maxlength to that value. Here is an example of the value I'm looking to retrieve.
public class DogClass
{
[StringLength(5)]
public string LegalName
{
}
You can use reflection to get this info. Below is a snippet that should get you started.
protected void GetStringLength(object objDog) {
// loop through each property in object
foreach (PropertyInfo pi in objDog.GetType().GetProperties())
{
// for each object property, get the SringLength tag (if there is one)
foreach (Attribute attribute in Attribute.GetCustomAttributes(pi, typeof(StringLengthAttribute), true))
{
// we'll assume there is only one
var stringLenVal = (attribute as StringLengthAttribute).MaximumLength;
break;
}
}
}

The Proper Class Design For Designing a Language Type System

I am designing a language for my own purposes. It will have two entities basically, functions and types. e.g.
Object1 = CreateObject1("param1", "param2", 23 ) //Line 1
Object3 = Object1 + Object2 //Line 2
Evaluate(Object3) //Line 3
Line 2 evaluates if object of type Object1 be "+" to Object2 and if yes then a resultant object will be created and will be assigned to Object3. The variable definitions are like var keyword in Java Script.
The design in my mind is like creating a base "Value" class (having primitive operations like add, subtract, multiply, divide etc) having concrete children each corresponding to different types which I plan to ingest in the language.
class Value{
Value add(Value value)
..
}
class Integer extends Value{
Value add(Value value){
//if value is compatible to add with Integer type then return the appropriate
//resultant object else throw exception.
}
}
I can create children classes like that easily but if a function changes the attributes of a object (like a member value be changed of a class) then I need to downcast to it to that type and update the appropriate property.
class ABC extends Value{
Value add(Value value){
//
}
private int X;
private int Y;
private int Z;
private string XYZ;
public setX(int x){
this.X = x;
}
.
.
}
ObjectABC = GetABC();
SetX(ObjectABC, 1)
In the implemenatiob of the function SetX(). I will be doing something like this:
ABC abc = (ABC)ObjectABC; //ObjectABC will be a Value type here.
abc.setX( 1 );
I want to get rid of this down casting thing. Can it be done? Please advise.
You could use double dispatch like so:
abstract class Value {
Value add(Value v) { throw new InvalidArgumentException("add", getClass(), v); }
Value addInteger(Integer i);
Value divide(Value) { throw new InvalidArgumentException("divide", getClass(), v); }
Value divideIntegerReversed(Integer i);
}
class Integer extends Value {
#Override
Value add(Value v) {
return v.addInteger(this);
}
#Override
Value addInteger(Integer other) {
// note the argument reversal but not worries because addition is commutative
return whtvr;
}
#Override
Value divide(Value v) {
return v.divideIntegerReversed(this);
}
#Override
Value divideIntegerReversed(Integer nom) {
// note that we now want `nom / this` and not `this / nom`
return wthvr;
}
}

Generate parameter list with userdefined types at runtime (using C#)

As part of my project, I am trying to build a web UI where user will select a method and pass the values. My program should be able to call the method dynamically and build a parameter list on runtime to pass it to the method.
I have created a comma separated list (string) of key and value pairs. This key/value pair is nothing but the parameter name and value of my method (methodname stored in a variable). Example: string params = "ID:123;Name:Garry;Address:addressObject;AddressLine:108 Plaza Lane;City:Avenel;State:NJ;Zip:07001;". Where ID and Name are simple string varaibles while Address is user defined type. What follows after Address i.e. AddressLine, City, State and Zip is elements of Address object. And my method definition is
public string GetInfo(string ID, string Name, Address addressObject)
{
//return something;
}
I am dynamically calling the method (GetInfo) that is stored in sMethodName variable using DynamicProxy like :
string sMethodName = "GetInfo";
object result = (object) proxy.CallMethod(sMethodName, arguments);
Challenge is how to pass the argument list dynamically? Till now I am just able to extract the values from the csv variable into NamedValueCollection. Here is the code:
public static void StoreParameterValues(string param)
{
nvc = new NameValueCollection();
param = param.TrimEnd(';');
string[] parameters = param.Split(new char[] { ';' });
foreach (string val in parameters)
{
string[] keyValue = val.Split(new char[] { ':' });
nvc.Add(keyValue[0], keyValue[1]);
}
}
..and here is the code that tries to build the parameter:
string methodName = "GetInfo";
DynamicProxyFactory factory = new DynamicProxyFactory("http://../myservice.svc");
string sContract = "";
foreach (ServiceEndpoint endpoint in factory.Endpoints)
{
sContract = endpoint.Contract.Name;
}
DynamicProxy proxy = factory.CreateProxy(sContract);
string[] values = null;
// Create the parameter list
object[] arguments = new object[nvc.Count];
int i = -1;
foreach (string key in nvc.Keys)
{
values = nvc.GetValues(key);
foreach (string value in values)
{
arguments[++i] = value;
}
}
object result = (object) proxy.CallMethod(methodName, arguments);
The above code works if I have simple primitive types but not sure how can I build the logic for any other userdefined types. How can I create a object dynamically of type stored in a variable? Not sure if I was able to put my question correctly. I hope so :)
Edit: 01/19/2011: Applied the suggestion from Chris - using Reflection instead of ComponentModel.
I have converted the code to make it more generic. This works now for all primitive and custom types (resursion). Code snippet below:
private object BuildParameterList(Type type)
{
object item = new object();
item = Activator.CreateInstance(type);
PropertyInfo[] propArray = type.GetProperties(BindingFlags.Public|BindingFlags.Instance);
for (int i = 0; i < propArray.Length; i++)
{
PropertyInfo pi = (PropertyInfo)propArray[i];
////Check for custom type
if (IsCustomType(pi.PropertyType))
{
object item1 = BuildParameterList(pi.PropertyType);
pi.SetValue(item, item1, null);
}
else
{
if (property.ContainsKey(pi.Name))
{
pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
}
}
}
return item;
}
But if one of the property is Color (I just tested with Color type, will fail with other system types aswell-i guess), then it fails at the following line. Not sure how to handle system types - Color or something similar.
pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
Can you not find what types are expected by the method, by inspecting its ParameterInfos:
endpoint.Contract.ContractType.GetMethod(methodName).GetParameters();
and then instantiating the custom types using:
Activator.CreateInstance(parameterType);