Phlip [mailto:phlip2005@gmail.com]:
C# is really Java with some of the keywords
searched-and-replaced. And the license terms rewritten.
Since I don't think that most folks on this list are tracking what's happening in C#, and that many folks appreciate beautiful code, here's something that I hacked up in the latest version of C# (3.0) that we're shipping by the end of the year (betas of this are currently available).
These are extension methods, which is a static form of monkey patching. Here we're adding the SelectCustomAttributes<T> generic method to both Type and MethodInfo:
static class ExtensionMethods {
public static IEnumerable<T> SelectCustomAttributes<T>(this Type type) where T : Attribute {
return type.GetCustomAttributes(typeof(T), false).Cast<T>();
}
public static IEnumerable<T> SelectCustomAttributes<T>(this MethodInfo method) where T : Attribute {
return method.GetCustomAttributes(typeof(T), false).Cast<T>();
}
}
Here's a LINQ query that uses the Reflection APIs (not modified at all to support LINQ) to retrieve all of the methods on type t that are marked with the RubyMethodAttributecustom attribute. Note the call to the extension method SelectCustomAttributes on the MethodInfo object returned from t.GetMethods().
Type t = GetTypeFromSomewhere();
var methods = (from m in t.GetMethods()
where m.IsDefined(typeof(RubyMethodAttribute), false)
select m.SelectCustomAttributes<RubyMethodAttribute>().First());
Note the use of the var keyword to infer the type of custom attributes (pretty obvious here, but sure beats typing it) from the query.
This code is part of a little utility that I wrote in IronRuby to determine how many methods that we have implemented in our libraries. Once I get SVN unwedged after my adventures yesterday you can grab that code to take a closer look.
Scott Hanselman also posted a version of my utility on his blog: http://www.hanselman.com/blog/TheWeeklySourceCode8.aspx
BTW, I'm fairly certain that you can't do this in Java today, but I could be mistaken.
-John