samedi 28 février 2015

Get methods with attribute and subscribe them to an event

How would one get all the methods that have a certain attribute applied to them through reflection, and then subscribe those methods to an event?


Class whose method is loaded through reflection:



public class EventsAndStuff
{
[DoStuffEvent]
public void OnDoStuff(object sender, DoStuffEventArgs e)
{
// Do Stuff
}
}


When the loading program starts, how would I subscribe OnDoStuff() to an event DoStuffEvent, so that when DoStuffEvent is invoked, it would call OnDoStuff and any other methods with a DoStuffEventAttribute applied?


I suspect this has to do with MethodInfo.CreateDelegate() but the MSDN documentation isn't particularly clear.


Most of the similar questions involve subsribing a non-reflection method to a reflection-loaded event. How could one do the reverse?






Java.lang.Class.cast doesn't return a casted object

I am trying to cast an object to its superclass using Java.lang.Class.cast but I get the same object. What can be the reason?


This is the code I'm running:



public static void parse(Object obj)
{
// parse all super classes
Class<?> clazz = obj.getClass().getSuperclass();
if (!clazz.equals(prevClass))
{
prevClass = clazz;
Object castedObj = clazz.cast(obj);
parse(castedObj);
}
fillObject(obj);
}


but when passing to parse an object of dynamic type B, where B extends A, castedObj is equal to obj. But I want castedObj to be a new object of dynamic type A because the parse method relies on that fact (iterates on the fields of the dynamic type class).






C# reflection, lambda?

I need to do this using reflection:



@Html.Grid((IEnumerable<MyType>)list).Columns(columns =>
{
columns.Add(foo => foo.Title)
.Titled("Custom column title")
.SetWidth(110);
columns.Add(foo => foo.Description)
.Sortable(true);
}).WithPaging(20)


Now I have var g which is object created after call @Html.Grid((IEnumerable<MyType>)Model) using refletion:



var method = typeof(GridMvc.Html.GridExtensions).GetMethods()
.Where(mi => mi.Name == "Grid")
.ElementAt(0)
.MakeGenericMethod(new Type[] { t });
var g = method.Invoke(null, new object[] { Html, list });


So I need do something like:



g.Columns(columns =>
{
columns.Add(foo => foo.Title)
.Titled("Custom column title")
.SetWidth(110);
columns.Add(foo => foo.Description)
.Sortable(true);
}).WithPaging(20)


using reflection.


Can someone provide example code to do this?






vendredi 27 février 2015

How to iterate through a struct in go with reflect

I have a specific struct that contains some url parameters, I want to build a url parameters string using reflect to iterate through the struct field, so that I wont care about what's the struct really contains.


Let's say I have a struct like this:



type Student struct {
Name string `paramName: "username"`
Age int `paramName: userage`
}


And I assign a student like this:



s := Student{
Name : "Bob",
Age : 15,
}


I want to build a query parameter string like this for this student instance:



username=Bob&userage=15


So far I have got:



func (s Student) buildParams() string {
st := reflect.TypeOf(s)
fieldCount := st.NumField()
params := ""
for i := fieldCount; i > 0 ; i-- {
params = params + "&" + st.Field(i).Tag.Get("paramName") + "=" + st.Field(i).Name
}
return params
}


But s.buildParams() gets me nothing, not event the tag value of paramName in each field :-(


So How can I do this?






Parse CSV file into List of Object arrays in java

I'm trying to parse a csv file into a list of object arrays.


Here is one example of the csv file



Type.Country,Type.Device,Sequence.id
US,PC,1
US,Tablet,2
UK,PC,3


I want to get a List list where each Object[] will contain two objects, Type and Sequence. So I can call the following code to get the output:



print(list.get(1)[1].getId());


output: 2


I created 2 POJO classes: Type and Sequence but the question is how can I parse the header information and get the column ids mapped to the POJO fields. It's easy to hard code the logic. But the csv files changes very often and I want to modify only the POJO classes to accommodate those changes, leaving the mapping logic general and unchanged.


I used OpenCSV to get the lines from csv but ran into trouble parsing the headers. Reflection can help but the code will be very messy. Is there any other open source tool that can help?






Array not equal to null when assigned null

arguments is not equal to null. Or there might be something else that I am missing.


The purpose of the code is to take any given String and handle the three different cases.



  1. "doSomething" => invoke doSomething()

  2. "doSomethingElse,2" => invoke doSomething(2)

  3. "doSomethingElsePlease,3,4" => invoke doSomething(3,4)


Number 2 and 3 can both be handled with varargs and passing the arguments as an array. Number 1 is were the problem occurs. The error that occurs is that


h("doSomething"); is trying to call for doSomething(null) {...}



private void h (String abc) {
String method = (abc.indexOf(",") == -1) ? abc: abc.substring(0, abc.indexOf(","));
System.out.println("Method: |" + method+"|");
String[] arguments = (abc.indexOf(",") == -1) ? null : abc.substring(abc.indexOf(",")).split(",");
System.out.println("Arguments: " + Arrays.toString(arguments));

try {
if (arguments == null) {
this.getClass().getMethod(method, String.class).invoke(this);
} else {
System.exit(0);
this.getClass().getMethod(method, String.class).invoke(this, Arrays.asList(arguments));
}
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException
| SecurityException e) {
e.printStackTrace();
}
}





Instantiate all properties and sub properties in an object (C#.net)

I have an object (x) with about 100 properties. Most of these properties are reference types that will need to be instantiated before I can do anything with x. Also, many of the properties on x will have properties that will also need to be instantiated.


I've thought to use reflection and recursion, but I'm still a little bit stuck on how the implementation would work. My current implementation involves looping through the PropertyInfo Array, and using SetValue from Activator.CreateInstance. As I drill down through x, I'm getting a lot of exceptions:



  • No parameterless constructor defined for this object.

  • Cannot create an abstract class.

  • Property set method not found.


Should I just account for these cases, or is there a better way to be doing this? Ultimately, it's not assigning values to everything I need still. Thanks for your help.






Instantiate and store generic arrays

Good day everyone. My problem has been discussed many times on SO, but i cant find answer anyway. So, I need to store array of generics in my generic class instance:



public class GenericArrayStorage<Item> implements Iterable<Item> {

private Item[] storage;
....
}


Obviously, I cant work with storage like with array of concrete objects (my IDE shows error Generic array creation on new Item[]). After some research i wrote this code:



@SuppressWarnings("unchecked")
public GenericArrayStorage() {
ParameterizedType genericSuperclass =
(ParameterizedType) getClass().getGenericSuperclass(); //error
Class clazz = (Class) genericSuperclass.getActualTypeArguments()[0];
storage = (Item[]) Array.newInstance(clazz, 10);
}


But this leads to following error: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType


I said OK and wrote this:



@SuppressWarnings("unchecked")
public GenericArrayStorage() {
ParameterizedType pt =
(ParameterizedType) getClass().getGenericInterfaces()[0];
Class clazz = (Class) pt.getActualTypeArguments()[0]; //error
storage = (Item[]) Array.newInstance(clazz, 10);
}


This one causes another exception: java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class. Sad but true.


Then I added .getClass() to pt.getActualTypeArguments()[0] and my constructor now don't throw any errors. However, when i try to work with this array after new GenericArrayStorage<Integer>(), it throws following: java.lang.ArrayStoreException: java.lang.Integer. This line causes exception: storage[0] = new Integer(1);


So, how could i work with generic array?






Java call method after class is initialized

I have a class X which is extended by various classes. X needs to know each subtype that exists of it at runtime. So my idea was to create a static method "static init()" in X that takes a Class as parameter. The problem is that a subclass of X is required to be initialized via its static-init-blocks before the call to init() happens. X for example may discover some of the static fields of the subclass which may be of any declared type. So take this code for example:



class X {
X() {
/*This would be one idea but does not work
in this concrete example.*/
init(getClass());
}
static void init(Class<? extends X> c) {
if(c.getDeclaredField("a").get(null) == null) {
throw new AssertionError();
}
}
}

class Y extends X {
static X a = new X();
static {
/*Another idea. Works totally fine but
I dont want to trust subclasses that
they do that correctly*/
init(Y.class);
}
}


So what I am looking for is a way to somehow get my init()-method called as the last step in the static initialization of a class. Or any other way to prevent the AssertionError from happening.






Why Type.GetType() return null for concatenated strings? [on hold]

I have this code:



string x = "DimensionUpdater.Tasks."+className;
string y = "DimensionUpdater.Tasks.DownloadDimensionUpdateTask";
var type = Type.GetType(x);
var type2 = Type.GetType(y);
var task = Activator.CreateInstance(type);


As below the on the image visible, the x and y variables are totally the same, but Type.GetType() return with null for x


Why Type.GetType() return null for a string value which was concatenated? And what is the workaround for this?







Can I tell ReflectionClass constructor to be case sensitive?

I have encountered a very interesting problem. I have two classes: APISession and ApiSession. I have an API class as well, which has a method, like this:



public static function request($category, $name, $params) {
$params["Response"] = new APIResponse();
$class = new ReflectionClass("API".$category);
return $class->getMethod($name)->invoke(null, $params);
}


I am calling the method:



$result = API::request("Session", "Check", array());


Naturally, I expect this to execute the Check method of the APISession class, however, I receive the following problem:



Fatal error: Uncaught exception 'PHPErrorException' with message 'Exception 'ReflectionException' with message 'Method Check does not exist'



I have checked the source of the problem and it is caused by the fact that the request is reaching ApiSession instead of APISession, despite the fact that the string passed to it is "APISession". My question is: is it possible to tell the ReflectionClass constructor to be case-sensitive?






how to get name and value of each parametes in java method?

I would like to get the name of each parameter and value coming to my method in java. I searched about it but I could not find something to help me. Can you show me a solution. I have a method as below



public HashMap<String, Object> putallinMap(Object...pars){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(pars[0].{name}, pars[0].{value});
return map;
}


This is How I call the method above.



String str1 = "Hello world!";
int myint = 55;
double myDouble = 11.5;
...// there can be other primitive types, long, short, Double etc.

HashMap<String, Object> map attrInMap = putallinMap(str1, myint, myDouble);


Sow What I expect to have a hasmap like below.



{"str1":"Hello world!", "myint" : 55, "myDouble": 11.5}





Loop field with reflection in class and call a function on a interface

I'm trying to loop my IRepository field in my class XmlSerialization with the use of Reflection. I'm not able to define a IRepository in foreach loop instead i tried with var. But i can then not call IRepository.Save, Somehow i ned to filter the generic IRepository in the foreach loop.


The type arguments for method 'Fle.SQLServer.XmlFiles.Notifier.XmlSerialization.Save(Fle.SQLServer.Core.Services.IRepository)' cannot be inferred from the usage. Try specifying the type arguments explicitly.


I understand my problem but cant fix it.


I want to loop my IRepository fields on XmlSerialization and call save without calling each fields in the class.



using Fle.SQLServer.Core.Model;
using Fle.SQLServer.Core.Services;

namespace Fle.SQLServer.XmlFiles.Notifier
{
public class XmlSerialization : INotifier
{
private readonly IRepository<BackupDeviceLocationData> _repositoryBackupDeviceLocation;
private readonly IRepository<BackupHistoryData> _repositoryBackupHistory;
private readonly IRepository<DatabaseSizesData> _repositoryDatabaseSizes;
private readonly IRepository<DiskSystemData> _repositoryDiskSystem;
private readonly IRepository<FailedDatabaseJobsData> _repositoryFailedDatabaseJobs;
private readonly IRepository<DatabaseReplicationData> _repositoryDatabaseReplication;
private readonly IRepository<DatabaseLongRunningJobData> _repositoryDatabaseLongRunningJob;
private readonly IRepository<DatabaseSystemData> _repositoryDatabaseSystem;
private readonly IRepository<DiskBackupData> _repositoryDiskBackup;
private readonly IRepository<SqlServerAgentEventLogData> _repositorySqlServerAgentEventLog;
private readonly IRepository<SqlServerEventLogData> _repositorySqlEventLog;
private readonly IRepository<DatabaseOwnerData> _repositoryDatabaseOwner;
private readonly IRepository<RecoveryModelData> _repositoryRecoveryModel;
private readonly IRepository<BelongToSystemData> _repositoryBelongToSystem;

public XmlSerialization(IRepository<BackupDeviceLocationData> repositoryBackupDeviceLocation,
IRepository<BackupHistoryData> repositoryBackupHistory,
IRepository<DatabaseSizesData> repositoryDatabaseSizes,
IRepository<DiskSystemData> repositoryDiskSystem,
IRepository<FailedDatabaseJobsData> repositoryFailedDatabaseJobs,
IRepository<DatabaseReplicationData> repositoryDatabaseReplication,
IRepository<DatabaseLongRunningJobData> repositoryDatabaseLongRunningJob,
IRepository<DatabaseSystemData> repositoryDatabaseSystem,
IRepository<DiskBackupData> repositoryDiskBackup,
IRepository<SqlServerAgentEventLogData> repositorySqlServerAgentEventLog,
IRepository<SqlServerEventLogData> repositorySqlEventLog,
IRepository<DatabaseOwnerData> repositoryDatabaseOwner,
IRepository<RecoveryModelData> repositoryRecoveryModel,
IRepository<BelongToSystemData> repositoryBelongToSystem)
{
_repositoryBackupDeviceLocation = repositoryBackupDeviceLocation;
_repositoryBackupHistory = repositoryBackupHistory;
_repositoryDatabaseSizes = repositoryDatabaseSizes;
_repositoryDiskSystem = repositoryDiskSystem;
_repositoryFailedDatabaseJobs = repositoryFailedDatabaseJobs;
_repositoryDatabaseReplication = repositoryDatabaseReplication;
_repositoryDatabaseLongRunningJob = repositoryDatabaseLongRunningJob;
_repositoryDatabaseSystem = repositoryDatabaseSystem;
_repositoryDiskBackup = repositoryDiskBackup;
_repositorySqlServerAgentEventLog = repositorySqlServerAgentEventLog;
_repositorySqlEventLog = repositorySqlEventLog;
_repositoryDatabaseOwner = repositoryDatabaseOwner;
_repositoryRecoveryModel = repositoryRecoveryModel;
_repositoryBelongToSystem = repositoryBelongToSystem;
}


public void Notify()
{
foreach (var field in this.GetType().GetProperties())
{
field.Save();
}
}
}
}





jeudi 26 février 2015

Validating arguments of private methods because of Reflection in C#

I am wondering whether it is necessary to validate once more the arguments passed to private methods of classes which without using Reflection would only be called by public methods in the same class.


If the private method instantiates an object that needs to be disposed (before something goes wrong because of bad arguments), an exception could be thrown (in which case the object would be disposed anyway), right?


I was viewing some of the source code of .NET (mainly the String and Stream classes). I found that some private methods arguments are verified with contracts, but in others no occur check.


Code that does not validate once more the arguments (taken from the String class). In this case a NullReferenceException can be thrown because of the trimChars argument.



[System.Security.SecuritySafeCritical] // auto-generated
private String TrimHelper(char[] trimChars, int trimType) {
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
int end = this.Length-1;
int start=0;

//Trim specified characters.
if (trimType !=TrimTail) {
for (start=0; start < this.Length; start++) {
int i = 0;
char ch = this[start];
for( i = 0; i < trimChars.Length; i++) {
// ... more code


A code that validates the arguments twice (once in public and once in private method) is this (taken from Stream class).



[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
if (destination == null)
throw new ArgumentNullException("destination");
// ... more code goes here
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}


private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
Contract.Requires(destination != null);
// ... more code
}


Which is the best practice, or does it depend on the situation - whether it is a class library that is only used in a specific project or it would be used in different contexts that can't be known in advance?






Property Tree of Component

Ive been trying to get the list of properties of control,



private void GetPropertyTree(object dependencyObject , TreeViewItem treeItem)
{
TreeViewItem currentItem = new TreeViewItem();
PropertyInfo[] properties = dependencyObject.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
TreeViewItem item = new TreeViewItem();
if (property.PropertyType.IsGenericParameter && dependencyObject.GetType().GetProperty(property.Name).GetValue(dependencyObject, null) != null)
item.Tag = dependencyObject.GetType().GetProperty(property.Name).GetValue(dependencyObject, null).GetType();
item.Header = property.Name;
if (treeItem == null)
{
propertyTreeView.Items.Add(item);
}
else
{
treeItem.Items.Add(item);
}
if (property.PropertyType.IsGenericParameter)
{
object obj = dependencyObject.GetType().GetProperty(property.Name).GetValue(dependencyObject, null);
if (obj != null)
{
Type value = obj.GetType();
// object instance = Activator.CreateInstance(property.PropertyType);
PropertyInfo[] sProps = value.GetProperties();
foreach (PropertyInfo sprop in sProps)
{
TreeViewItem sItem = new TreeViewItem();
sItem.Tag = value;
sItem.Header = sprop.Name;
item.Items.Add(sItem);
}
}
else
{

}
}
}
//throw new NotImplementedException();
}


I need to get the property's inner property also,but i've not used recursion to that,because in some cases it throws stackoverflow exception.. Here my problem is couldn't create instance of property type using Activator, it failed with no parameterless constructor method is defined exception. What can do to get the list of all possible inner properties in treeview.Please help me with your ideas. Ive basic knowledge of reflection.


Regards, kumar






Best practice - Setting a field without setters in a unit test

Let's say you have the following class you would like to test:



public class SomeService {
public String someMethod(ClassToTest objectToTest) {
return objectToTest.getSomeProperty();
}
}


The ClassToTest looks like this:



public class ClassToTest {
private String someProperty;

public getSomeProperty() {
return this.someProperty;
}
}


The assertion you would like to do can be the following:



String result = someService.someMethod(objectToTest);

assertThat(result).isEqualTo("someValue");


How can you make this test work?


1) Add a setter for 'someProperty' in the ClassToTest class. I don't think this a good solution because you don't change production code to make your tests work.


2) Use ReflectionUtils to set the value of this field. Test would look like this:



public class TestClass {
private SomeService someService;

@Test
public void testSomeProperty() {
ClassToTest objectToTest = new ClassToTest();
ReflectionTestUtils.setField(objectToTest, "someProperty", "someValue");

String result = someService.someMethod(objectToTest);

assertThat(result).isEqualTo("someValue");
}
}


3) You create an inner class in your test class that extends the ClassToTest class and adds the setter for this field. However, for this to work you will also need to change the ClassToTest class because the field should become 'protected' instead of 'private'. Test class might look like this:



public class TestClass {
private SomeService someService;

@Test
public void testSomeProperty() {
ObjectToTestWithSetters objectToTest = new ObjectToTestWithSetters();
objectToTest.setSomeProperty("someValue");

String result = someService.someMethod(objectToTest);

assertThat(result).isEqualTo("someValue");
}


public class ClassToTestWithSetters extends ClassToTest {
public setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
}
}


4) You use Mockito to mock ClassToTest. Seems fine if you only need to mock only one property in the class, but what if you need to mock like 10 properties are so. The test might look like this:



public class TestClass {
private SomeService someService;

@Test
public void testSomeProperty() {
ClassToTest objectToTest = mock(ClassToTest.class);
when(objectToTest.getSomeProperty()).thenReturn("someValue");

String result = someService.someMethod(objectToTest);

assertThat(result).isEqualTo("someValue");
}
}





PropertyAccessException: could not get a field value by reflection getter While using Hibernate

I have java class CourseOffered CourseTaker and Teacher where CourseTaker has Teacher's and CourseOffered's primary key as it's foreign key.


The CourseOffered Class Looks Following,( I have removed some basic constructors and Getters and Setters for make it small;)



package subHibernate.entity;

@Entity
@Table(name = "course_offered")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "CourseOffered.findAll", query = "SELECT c FROM CourseOffered c"),
@NamedQuery(name = "CourseOffered.findByCourseId", query = "SELECT c FROM CourseOffered c WHERE c.courseId = :courseId"),
@NamedQuery(name = "CourseOffered.findByCourseCode", query = "SELECT c FROM CourseOffered c WHERE c.courseCode = :courseCode"),
@NamedQuery(name = "CourseOffered.findByCourseTitle", query = "SELECT c FROM CourseOffered c WHERE c.courseTitle = :courseTitle"),
@NamedQuery(name = "CourseOffered.findBySession", query = "SELECT c FROM CourseOffered c WHERE c.session = :session"),
@NamedQuery(name = "CourseOffered.findBySemester", query = "SELECT c FROM CourseOffered c WHERE c.semester = :semester")})
public class CourseOffered implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "course_id")
private Integer courseId;
@Basic(optional = false)
@Column(name = "course_code")
private String courseCode;
@Basic(optional = false)
@Column(name = "course_title")
private String courseTitle;
@Basic(optional = false)
@Column(name = "session")
private String session;
@Basic(optional = false)
@Column(name = "semester")
private String semester;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "caCourseId")
private List<CourseTaker> courseTakerList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "crCourseId")
private List<CourseRegistration> courseRegistrationList;

public CourseOffered() {
}

//Some Constructors
// Getters and Setters which I deliberately Ignored as they are not
// Important here

@XmlTransient
public List<CourseTaker> getCourseTakerList() {
return courseTakerList;
}

public void setCourseTakerList(List<CourseTaker> courseTakerList) {
this.courseTakerList = courseTakerList;
}

@XmlTransient
public List<CourseRegistration> getCourseRegistrationList() {
return courseRegistrationList;
}

public void setCourseRegistrationList(List<CourseRegistration> courseRegistrationList) {
this.courseRegistrationList = courseRegistrationList;
}

public java.lang.Integer getPrimaryKey(){
return getCourseId();
}

}


And Teacher class looks like this,



@Entity
@Table(name = "teacher")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Teacher.findAll", query = "SELECT t FROM Teacher t"),
@NamedQuery(name = "Teacher.findByTeacherId", query = "SELECT t FROM Teacher t WHERE t.teacherId = :teacherId"),
@NamedQuery(name = "Teacher.findByTeaCode", query = "SELECT t FROM Teacher t WHERE t.teaCode = :teaCode"),
@NamedQuery(name = "Teacher.findByTeaPassword", query = "SELECT t FROM Teacher t WHERE t.teaPassword = :teaPassword"),
@NamedQuery(name = "Teacher.findByTeaName", query = "SELECT t FROM Teacher t WHERE t.teaName = :teaName"),
@NamedQuery(name = "Teacher.findByTeaEmail", query = "SELECT t FROM Teacher t WHERE t.teaEmail = :teaEmail"),
@NamedQuery(name = "Teacher.findByTeaDegignation", query = "SELECT t FROM Teacher t WHERE t.teaDegignation = :teaDegignation")})
public class Teacher implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "teacher_id")
private Integer teacherId;
@Basic(optional = false)
@Column(name = "tea_code")
private String teaCode;
@Basic(optional = false)
@Column(name = "tea_password")
private String teaPassword;
@Basic(optional = false)
@Column(name = "tea_name")
private String teaName;
@Basic(optional = false)
@Column(name = "tea_email")
private String teaEmail;
@Basic(optional = false)
@Column(name = "tea_degignation")
private String teaDegignation;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "caTeacherId")
private List<CourseTaker> courseTakerList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "tgTeacherId")
private List<TeacherGroup> teacherGroupList;
public Teacher() {
}

// Some Constructors
// Getters And Setters Ignored

@XmlTransient
public List<CourseTaker> getCourseTakerList() {
return courseTakerList;
}

public void setCourseTakerList(List<CourseTaker> courseTakerList) {
this.courseTakerList = courseTakerList;
}

@XmlTransient
public List<TeacherGroup> getTeacherGroupList() {
return teacherGroupList;
}

public void setTeacherGroupList(List<TeacherGroup> teacherGroupList) {
this.teacherGroupList = teacherGroupList;
}
}


And Finally CourseTaker Class



@Entity
@Table(name = "course_taker")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "CourseTaker.findAll", query = "SELECT c FROM CourseTaker c"),
@NamedQuery(name = "CourseTaker.findByCourseTakerId", query = "SELECT c FROM CourseTaker c WHERE c.courseTakerId = :courseTakerId")})
public class CourseTaker implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "course_taker_id")
private Integer courseTakerId;
@JoinColumn(name = "ca_course_id", referencedColumnName = "course_id")
@ManyToOne(optional = false)
private CourseOffered caCourseId;
@JoinColumn(name = "ca_teacher_id", referencedColumnName = "teacher_id")
@ManyToOne(optional = false)
private Teacher caTeacherId;

public CourseTaker() {
}

public CourseTaker(Integer courseTakerId) {
this.courseTakerId = courseTakerId;
}

public Integer getCourseTakerId() {
return courseTakerId;
}

public void setCourseTakerId(Integer courseTakerId) {
this.courseTakerId = courseTakerId;
}

public CourseOffered getCaCourseId() {
return caCourseId;
}

public void setCaCourseId(CourseOffered caCourseId) {
this.caCourseId = caCourseId;
}

public Teacher getCaTeacherId() {
return caTeacherId;
}

public void setCaTeacherId(Teacher caTeacherId) {
this.caTeacherId = caTeacherId;
}
}


I also Have a CourseTakerService Class which looks like this,



public class CourseTakerService implements ICourseTakerService , LocatableService {

private static Logger log = LogService.getLogger(CourseTakerService.class);

public void init() {
}
public void destroy() {
}
/**
* Adds a new courseTaker to the database.
*
* @param model a data object
* @return CourseTaker a data object with the primary key
*/
public subHibernate.entity.CourseTaker addCourseTaker(subHibernate.entity.CourseTaker model) throws GenericBusinessException {
subHibernate.HibernateQueryHelper hibernateTemplate = new subHibernate.HibernateQueryHelper();
try {
hibernateTemplate.save(model);
return getCourseTaker(model.getPrimaryKey());
} finally {
log.debug("finished addCourseTaker(subHibernate.entity.CourseTaker model)");
}
/**
*
* Retrieves a list of data object for the specified caTeacherId field. To
* use a wildcard search, use a % in the query.
*
* @param caTeacherId the field
* @return List of CourseTaker data objects, empty list in case no results
* were found.
*/
public java.util.List findCourseTakerByCaTeacherId(java.lang.Integer caTeacherId) throws GenericBusinessException {
subHibernate.HibernateQueryHelper hibernateTemplate = new subHibernate.HibernateQueryHelper();
try {
String queryString = "from " + CourseTaker.class.getName() + " e where e.caTeacherId like :caTeacherId ";
// Add a an order by on all primary keys to assure reproducable results.
String orderByPart = "";
orderByPart += " order by e.courseTakerId";
queryString += orderByPart;
Query query = hibernateTemplate.createQuery(queryString);
hibernateTemplate.setQueryParameter(query, "caTeacherId", caTeacherId);
List list = hibernateTemplate.list(query);
return list;
} finally {
log.debug("finished findCourseTakerByCaTeacherId(java.lang.Integer caTeacherId)");
}
}
}


When I call list = (List) courseTakerService.findCourseTakerByCaTeacherId(1); It produces the following Stack Trace [It is Guaranteed that courseTaker table has a row with courseTeacherId = 1 ]



27-Feb-2015 11:11:31.539 ERROR [http-nio-8084-exec-32] com.finalist.util.log.JDKLogger.error Error while getting the hibernate query list.
org.hibernate.PropertyAccessException: could not get a field value by reflection getter of subHibernate.entity.Teacher.teacherId
at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:62)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:344)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4537)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4259)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:209)
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:248)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:510)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:174)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:66)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:612)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1875)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1836)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1816)
at org.hibernate.loader.Loader.doQuery(Loader.java:900)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
at org.hibernate.loader.Loader.doList(Loader.java:2526)
at org.hibernate.loader.Loader.doList(Loader.java:2512)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
at org.hibernate.loader.Loader.list(Loader.java:2337)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:357)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at subHibernate.HibernateQueryHelper.list(HibernateQueryHelper.java:94)
at subHibernate.session.CourseTakerService.findCourseTakerByCaTeacherId(CourseTakerService.java:270)
at OffiAssignServlet.processRequest(OffiAssignServlet.java:116)
at OffiAssignServlet.doPost(OffiAssignServlet.java:174)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field subHibernate.entity.Teacher.teacherId to java.lang.Integer
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:387)
at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:59)
... 53 more

subHibernate.exception.GenericBusinessException: Error while getting the hibernate query list.
at subHibernate.HibernateQueryHelper.list(HibernateQueryHelper.java:98)
at subHibernate.session.CourseTakerService.findCourseTakerByCaTeacherId(CourseTakerService.java:270)
at OffiAssignServlet.processRequest(OffiAssignServlet.java:116)
at OffiAssignServlet.doPost(OffiAssignServlet.java:174)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of subHibernate.entity.Teacher.teacherId
at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:62)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:344)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4537)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4259)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:209)
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:248)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:510)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:174)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:66)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:612)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1875)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1836)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1816)
at org.hibernate.loader.Loader.doQuery(Loader.java:900)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
at org.hibernate.loader.Loader.doList(Loader.java:2526)
at org.hibernate.loader.Loader.doList(Loader.java:2512)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
at org.hibernate.loader.Loader.list(Loader.java:2337)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:357)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at subHibernate.HibernateQueryHelper.list(HibernateQueryHelper.java:94)
... 29 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field subHibernate.entity.Teacher.teacherId to java.lang.Integer
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:387)
at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:59)
... 53 more





Getting the element name from wsdl dll using reflection C#

I am writing a parser which would determine all the properties for a web method. This particular static metnod would return us an array of xelement.


My function is



private static XElement[] GetProperty(Assembly assembly, string typeName)
{
var result = new List<XElement>();
if (typeName.EndsWith("[]"))
typeName = typeName.Replace("[]", "");
var type = assembly.GetExportedTypes().FirstOrDefault(t => t.Name == typeName);

foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.SetProperty))
{
if (prop.PropertyType.IsPrimitive())
result.Add(new XElement(prop.Name, prop.PropertyType.Name.Trim('&')));
else
{

if (prop.PropertyType.Name.EndsWith("[]"))
{
if (assembly.GetExportedTypes().FirstOrDefault(t => t.Name == prop.PropertyType.Name.TrimEnd('[', ']')) != null)
{
XElement element = new XElement(string.Format("{0}", prop.Name));
element.Add(new XElement(string.Format("{0}", "a"), GetProperty(assembly, prop.PropertyType.Name)));
result.Add(element);
}

}
else
{
....
}

}

}


return result.ToArray();
}


while parsing for an array variable i am stuck. I am not sure how to get the value "PhoneNumber" and replace to the hard coded value "a"(element.Add(new XElement(string.Format("{0}", "a"), )))) which is described in xml "". This has to be done through reflection.



-<xsd:complexType name="GeneralType">


-<xsd:sequence>


-<xsd:element name="PhoneNumbers">


-<xsd:annotation>

<xsd:documentation>Contains the claimants phone number(s).</xsd:documentation>

</xsd:annotation>


-<xsd:complexType>


-<xsd:sequence>


-<xsd:element type="person:TelephoneStructure" name="PhoneNumber" minOccurs="0" maxOccurs="unbounded">


-<xsd:annotation>

<xsd:documentation>An individual number using TelephoneStructure where [TelUse specified the use of this particular number, work or home, TelMobile indicates whether this number is a mobile yes or no, TelPreferred in the case of the claimant having multiple telephone numbers, is this number preferred? yes or no.</xsd:documentation>

</xsd:annotation>

</xsd:element>

</xsd:sequence>

</xsd:complexType>

</xsd:element>


-<xsd:element type="LocalAuthorityIdType" name="ClaimReferenceId" minOccurs="0">


-<xsd:annotation>

<xsd:documentation>The back office Claim Reference Id.</xsd:documentation>

</xsd:annotation>

</xsd:element>


-<xsd:element type="LocalAuthorityIdType" name="CouncilTenantRentAccount" minOccurs="0">


-<xsd:annotation>

<xsd:documentation>The back office Council Tenant Rent Account Id.</xsd:documentation>

</xsd:annotation>

</xsd:element>


-<xsd:element type="LocalAuthorityIdType" name="CouncilTaxAccount" minOccurs="0">


-<xsd:annotation>


Can some one please help me on this. I know i can do serialization..






pass a function to java dynamic proxy's invoke function using args parameter

Suppose I have below scala code using dynamic proxy (my only question is embedded):



trait IClient
{
def execute[R](func: IClient=>R) : R
}

class MyInvocationHandler extends InvocationHandler {
def invoke(proxy: Any, method: Method, args: Array[AnyRef]): AnyRef = {
// can I restore func passed by args and execute it here?
null
}
}

class factory[P: ClassTag]() {
val clientClass = implicitly[ClassTag[P]].runtimeClass

def getProxy() : P = java.lang.reflect.Proxy.newProxyInstance(
getClass.getClassLoader,
Array(clientClass),
new MyInvocationHandler()).asInstanceOf[P]
}

def main(): Int = {
// can the function (a: IClient)=>{0} be passed to invoke to execute?
(new factory[IClient]).getProxy().execute((a: IClient) => { 0 })
}


Appreciate any clue!






pass a function to java dynamic proxy's invoke function using args parameter

Suppose I have below scala code using dynamic proxy (my only question is embedded):



trait IClient
{
def execute[R](func: IClient=>R) : R
}

class MyInvocationHandler extends InvocationHandler {
def invoke(proxy: Any, method: Method, args: Array[AnyRef]): AnyRef = {
// can I restore func passed by args and execute it here?
null
}
}

class factory[P: ClassTag]() {
val clientClass = implicitly[ClassTag[P]].runtimeClass

def getProxy() : P = java.lang.reflect.Proxy.newProxyInstance(
getClass.getClassLoader,
Array(clientClass),
new MyInvocationHandler()).asInstanceOf[P]
}

def main(): Int = {
// can the function (a: IClient)=>{0} be passed to invoke to execute?
(new factory[IClient]).getProxy().execute((a: IClient) => { 0 })
}


Appreciate any clue!






Reflection: casting reflected type to generic with type as string and iterating over it

I have scoured around StackOverflow and found multiple related questions, but none that answers it 'completely'. I might be wrong in my understanding, but wanted to check it -


I have a class



public class Foo
{
public List<Bar> Bars = new List<Bar>();
}

public class Bar
{
}


Due to some reflection craziness happening, this List is getting passed only as an object -



Foo f = new Foo();
object o = f;
CheckItem(o, "Bars");

// CheckItem has no clue about Bar class and is thus passed the 'Bars' Field name
public void CheckItem(Object obj, string fieldName)
{
var value = obj.GetType().GetField(fieldName).GetValue(obj); // returns f.Bars into value as object

foreach (var bar in value.Bars) // won't compile as value is type object
}


so, I use MakeGenericType and Activator.CreateInstance magic



var genericClass = typeof(List<>).MakeGenericType(new[] {value.GetType().FieldType.GetGenericArguments()[0]}); // makes a generic of type List<Bar>
var o = Activator.CreateInstance(genericClass); // o is again of type object
foreach (var bar in o.Bars) // will fail again


SO - How do I call the foreach loop to iterate over the members. Every example I have seen around MakeGenericType ends at just creating the object o, none talks about how to access its members, esp in a foreach loop like above.


Appreciate any inputs.


Thanks






How to preserve caller informaion in java dynamic proxy

Suppose I have below pseudo scala code using dynamic proxy:



trait IClient {
def multiply(a : Int) = Int
}

class MyInvocationHandler extends InvocationHandler {
def invoke(proxy: Any, method: Method, args: Array[AnyRef]): AnyRef = {
//do nothing
}}

class factory[P]() {
val clientClass = implicitly[ClassTag[P]].runtimeClass

def getProxy() : P = java.lang.reflect.Proxy.newProxyInstance(
getClass.getClassLoader,
Array(clientClass),
new MyInvocationHandler()).asInstanceOf[P]
}

def main(): Int = {
(new factory[IClient]).getProxy().multiply(1)
}


Now I want to pass below information to MyInvocationHandler.invoke: 1. multiply(1)'s caller method "main()" 2. multiply(1)'s caller class where main() resides 3. multiply function name


I don't want to add more parameters into multiply(1) such as



multiply(callerClassName, callerMethodName, calleeName, 1)


Is there a way to pass these manifest info to MyInvocationHandler.invoke while keeping original interface multiply(Int):Int?


Appreciate any clue!






How to get the FieldInfo of a field from the value

I want to access the FieldInfo, for the CustomAttributes that are on a field, and other purposes, but I'd prefer not to use a string to access that field, nor to have to run through all the fields in a class.


If I simply have,



class MyClass
{
#pragma warning disable 0414, 0612, 0618, 0649
private int myInt;
#pragma warning restore 0414, 0612, 0618, 0649

public MyClass()
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Console.WriteLine( GetType().GetField("myInt", flags) );

foreach( FieldInfo fi in GetType().GetFields(flags) )
{
Console.WriteLine( string.Format("{0} {1} {2}", fi.Name, myInt, fi.GetValue(this) ) );
}
}
}


I know I can access the FieldInfo of "myInt" directly via the "GetField" function, if I have the string of it's name, or cycling through "GetFields", that would again rely upon having the string "myInt" to ensure you've the right field.


Is there any sort of magic that's available like ref myInt, or out myInt, or some keyword that I don't know about yet which would give me access, or am I limited to needing the string name to get it?






Creating objects dynamically from Interface or assembly C#

Lets say I have some interface that looks like the below



public interface IPerson
{
Person GetPerson(string name);
Person SetPerson(Person p);
}


And my person object has some nested objects and maybe it inherits from a base class.



public class Person : SomeBaseClass
{
public Name fullName {get;set;}
// some other stuff
}


Now lets say all the above gets compiled to an assembly (dll). Is it possible to instantiate the Person Object on the fly using reflection?



void Main()
{
Type type = typeof(IPerson);
var instance = Activator.CreateInstace(t);
// can't access properties of Person from instance.. :(
// I wan't to populate all the properties of the object on the fly
// but can't
}


Basically I want to reference the dll or load the assembly dynamically iterate over all the objects in said assembly, create the objects and populate their properties, and finally do something with those objects and their properties. Is this possible? Seems I only have access to Person.Name when I make a static cast.



var oops = (Person)instance; // now I can access. but I dont want to have to cast!





How to get return type from any Method with Guava?

What I understand from the official Guava's TypeToken wiki is we can get the return type of a method even if it is defined by a type argument. But I cannot manage to retrieve the returned type of a Method .


If I have an instanced List<String>, how can I do to get String.class from the get() method instead of E?


I know Java does type erasure during compile-time (i.e. the type argument is not available during runtime). Maybe I'm wrong, and Guava cannot retrieve the expected type of a method from a instanced class...






Invokable.getReturnType(): cannot reproduce Guava's example from the official wiki

In the official Guava's TypeToken wiki, there is the following example:



Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod);
invokable.getReturnType(); // String.class


How getMethod is set?


I tried the following examples:




  1. First try:



    List<String> list = new ArrayList<String>();
    Class[] arg = { int.class };
    Method getMethod = list.getClass().getMethod("get", arg);
    Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod);
    System.out.println(invokable.getReturnType());


    It crashed with the following message:



    Exception in thread "main" java.lang.IllegalArgumentException: public java.lang.Object java.util.ArrayList.get(int) not declared by java.util.List<java.lang.String>
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:145)
    at com.google.common.reflect.TypeToken.method(TypeToken.java:495)
    at tmp.LaunchClass.main(LaunchClass.java:28)



  2. Second try (a little bit different though):



    List<String> list = new ArrayList<String>();
    Class[] arg = { int.class };
    Method getMethod = list.getClass().getMethod("get", arg);
    // changed here
    Invokable invokable = TypeToken.of(list.getClass()).method(getMethod);
    System.out.println(invokable.getReturnType());


    Doesn't crash, but doesn't return the expected result. Returned E. Expected result: String.class (as in the official wiki).








Invokable.getReturnType(): cannot reproduce Guava's example from the official wiki

In the official Guava's TypeToken wiki, there is the following example:



Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod);
invokable.getReturnType(); // String.class


How getMethod is set?


I tried the following examples:




  1. First try:



    List<String> list = new ArrayList<String>();
    Class[] arg = { int.class };
    Method getMethod = list.getClass().getMethod("get", arg);
    Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod);
    System.out.println(invokable.getReturnType());


    It crashed with the following message:



    Exception in thread "main" java.lang.IllegalArgumentException: public java.lang.Object java.util.ArrayList.get(int) not declared by java.util.List<java.lang.String>
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:145)
    at com.google.common.reflect.TypeToken.method(TypeToken.java:495)
    at tmp.LaunchClass.main(LaunchClass.java:28)



  2. Second try (a little bit different though):



    List<String> list = new ArrayList<String>();
    Class[] arg = { int.class };
    Method getMethod = list.getClass().getMethod("get", arg);
    // changed here
    Invokable invokable = TypeToken.of(list.getClass()).method(getMethod);
    System.out.println(invokable.getReturnType());


    Doesn't crash, but doesn't return the expected result. Returned E. Expected result: String.class (as in the official wiki).








Intercept Method/Property call in c#

In the code below I have a class Foo which is called (without an interface) by my main method. There is no backing field or setter for the property, instead it calls a private method. Foo cannot be changes, nor can the usage of foo be changed to an IFoo interface.


- How do I change the value of foo.FooValue?


- Is there anything in the System.Reflection, System.Reflection.Emit, .NET standard libraries etc (unsafe code, whatever) that I can include in a unit test to change the return value?


I appreciate if there is something it's bound to be quite "evil", but I am interested in "evil" answers.



public class Program
{
public static void Main(){

Foo foo = new Foo();
int bar = foo.FooValue;
}
}

public class Foo{

public int FooValue
{
get
{
return this.FooMethod();
}
}

private int FooMethod
{
return 0;
}
}


Related questions:


How to set value of property where there is no setter - Related but unanswered - Maybe the answer is "no", but I'm not convinced by the top answer which merely points out you can't achive this by changing a (non-existent) backing field.


Intercept call to property get method in C# - Interesting. Not sure whether this is my answer and if it is, not sure how it could be used in a unit test.






ASP.NET universal controller for database dictionaries (using Entity Framework)

I've got some models that only have two fields: Id and Name. All this models inherit from IDbDictionary interface.


My goal is to make "universal" controller for CRUD operations for this models. My problem is how to (using EF) modify database table by name. For example, there is method



[HttpPost]
public ActionResult Create(IDbDictionary newRecord, string collectionName)
{
if (ModelState.IsValid)
{
db.<collectionName>.Add(newRecord);
db.SaveChanges();
return View("Success");
}

return View("Create", newRecord);
}


Is there a way to do it the way I described? I thought about reflection, but I've no idea how to do this.


Regards,

C






Append code to a function in C#

In my project, I am used a lot of classes and methods. Project is working fine. But now I need a performance optimization. I want a logging option for track execution time of each method. Changing each function code is not good.


So my question is, is there any option for append/inject some code block to every method, without touch the existing code; I need a log entry before and after execution of a method with time.


I am not prefer a third party tool.


Thanks in advance..






mercredi 25 février 2015

Reflect Map in Java

In Java, having shared storage:



final Map<String, Car> cars = (numberOfThreads == 1)
? new HashMap<String, Car>()
: new ConcurrentHashMap<String, Car>();


then in the run() method of a thread worker class I want to store concurrently data into the cars map. For that I need to downcast to an appropriate hashmap instance. I could use if (numberOfThreads == 1) but I guess it is possible to reflect the cars object - how can I use Java Reflection API here?






It was just another day with .NET. Until I had to get generic method of a static class with a generic parameter, using reflection for serialization. Doesn't sound so bad. GetRuntimeMethod("x", new[] { type }), as usual should do the trick, or so I thought.


Now, this method keeps returning null for the following variant: public static Surrogate<T> BuildSurrogate<T>(List<T> collection).


So, a quick copy to LinqPad, and a GetRuntimeMethods run later, it seemed to have all the methods as expected. Naturally, I thought perhaps, something wasn't right with the behavior of GetRuntimeMethod, so, I whipped up a quick extension, GetRuntimeMethodEx that iterates through, and to my surprise, it failed. What? How could that fail. GetRuntimeMethods has the exact the methodInfo I need.


So, I ended up breaking up the extension into parts to understand what exactly is going on, as in the code below. And it turns out (cType != cGivenType) always ended up true.


But a quick inspection, shows they were the same 'apparent' type - List<T>. Now being utterly confused, a diff on the dump of the two typeof(List<T>), and it turns out they were not the same!


The MetadataToken of the two were exactly the same. However the RuntimeTypeHandle were different. The given type had the correct AssemblyQualifiedName, and FullName, belonging to System.Collections.Generic.List``1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. Great. But oddly enough, the type on the generic method, had both of them as "null"! So, basically, the List<T> is a magical type with no corresponding assembly(!?). It exists, but doesn't. How fascinating!


Here's a quick dump of the diff between the two, that's relevant.


Image of the differences


Note the GenericTypeParameters, and IsGenericTypeDefinition - They are the ones which seem to make perfect sense. The oddities aside, now how could one create a Type that matches this type on the MethodInfo? Potentially, the compiler expects a generic type of List<> with the generic parameter T - The only problem is, you can't literally make a generic type with T. The T has to be a type of something, which now invalidates the equality.



private void Main()
{
var type = typeof (List<>);
var m = typeof (Builders).GetRuntimeMethods();
var surrogateBuilder = typeof (Builders)
.GetRuntimeMethodEx("BuildSurrogate", new[] {type});
}

static class Builders
{
public static Surrogate<T> BuildSurrogate<T>(List<T> collection)
{
return new Surrogate<T>
{
Items = collection.ToArray(),
};
}

public class Surrogate<T>
{
public IEnumerable<T> Items;
}
}

public static class ReflectionExtensions
{
public static MethodInfo GetRuntimeMethodEx(
this Type type, string name, params Type[] types)
{
var m = type.GetRuntimeMethods();
var res = (m.Where(t =>
{
var n = name;
return t.Name.Equals(n);
}).FirstOrDefault(t =>
{
var px = t.GetParameters().ToArray();
var currentTypes = px.Select(p => p.ParameterType).ToArray();
if (currentTypes.Length < 1) return false;
for (var i = 0; i < types.Length; i++)
{
var cGivenType = types[i];
for (var j = 0; j < currentTypes.Length; j++)
{
var cType = currentTypes[j];
if (cType != cGivenType) return false;
}
}
return true;
}));
return res;
}
}





Iterate recursivly over java object tree

I have a complexe java object of unknown class, I need to iterate over all inner objects to do some manipulations on them. Does there already exist a helper which does this for me and allows me to insert an strategy for any found inner object?


I need something that supports: - any depth of object tree - arrays and collections - cycles inside the references


Any idea?






Can I pass a subclass instance to a method which accepts superclass instance

I have a setup similar to this. When I try to call execRequest method using java Reflections and in parameterArray pass the subclass instance which is DelRequest I am getting an NoSuchMethodFound Exception



lClass.getMethod( "execRequest", parameterArray)


This is my basic setup kindly point where am i wrong and can it be done or not



class DelRequest extends Request {
private String msg;


/* getters and setters */
}

class Request {
}



class ExecuteRequest{
public static String execRequest(Request request){
/* request do something*/
}

}





Getting Id of a child object-attribute of a BeanPropertySqlParameterSource

I have a Question Bean:



public class Question implements IHaveId, IAuditable {

private long id;
private QuestionType questionType;
private String questionText;
private String questionHint;
private RenderMode renderMode;

...
Normal Bean getters and setters here
...

}


and another Answer Bean, note the two extra getters and setters for the Question Attribute : getQuestionId and setQuestionId



public class Answer implements IHaveId, IAuditable {

private long id;
private String answerValue;
private DataType dataType = DataType.UNKNOWN;
private Question question;

...
javabean getters and setters here
...

//Kindly note these extra two getters and setters
public Long getQuestionId() {

return question == null ? null : question.getId();
}

public void setQuestionId(Long questionId) {
if(questionId == null)return;
question = new Question();
question.setId(questionId);
}
}


I am using the Answer Bean as a BeanPropertySqlParameterSource when calling a Stored procedure using SimpleJdbcCall.



Map m = pspCreate.execute(in) = new BeanPropertySqlParameterSource(answer);



The parameters of the Stored procedure are the primitive type properties of the Answer Object with the id of the Object type properties.


For instance if a have a question_id parameter, JavaBean Reflection uses getQuestionId


How do I avoid this avoid adding the getQuestionId because it kind of duplicates the question Attribute?






How to access PowerShell host from C#

In a PowerShell profile, one can identify the PowerShell host in order to do appropriate setup for that host's environment. For example:



if ($host.Name -eq 'ConsoleHost')
{
Import-Module PSReadline
# differentiate verbose from warnings!
$privData = (Get-Host).PrivateData
$privData.VerboseForegroundColor = "cyan"
}
elseif ($host.Name -like '*ISE Host')
{
Start-Steroids
Import-Module PsIseProjectExplorer
}


I would like to be able to do the equivalent identification from a C# context primarily because PowerShell ISE does not support Console.ReadLine so I want to know if it is safe to use it in the current PS host's environment.


I first explored trying to get the output of the Get-Host cmdlet from within C# (per Invoking a cmdlet within a cmdlet). After I located the Microsoft.PowerShell.Commands.Utility assembly (under C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0) I could compile this but it yielded null...



var cmd = new Microsoft.PowerShell.Commands.GetHostCommand();
var myHost = cmd.Invoke();


...while this would not compile due to the InternalHost class being (ironically!) internal:



var cmd = new Microsoft.PowerShell.Commands.GetHostCommand();
var myHost = cmd.Invoke<System.Management.Automation.Internal.Host.InternalHost>();


Next, I then modified my cmdlet to inherit from PSCmdlet rather than Cmdlet (to allow access to the SessionState), so I could then access the PS host object like this:



var psVarObject = SessionState.PSVariable.GetValue("Host");


Of course, that returns a pure Object, which I then needed to cast to... oh, wait... it's still internal!... so this would not compile:



string psHost = ((System.Management.Automation.Internal.Host.InternalHost)psVarObject).Name;


Leaving me no alternative but to use reflection on a foreign assembly (horrors!):



string psHost = (string)psVarObject.GetType().GetProperty("Name").GetValue(psVarObject, null);


That works, but is less than ideal, because reflecting upon any 3rd-party assembly is a fragile thing to do.


Any alternative ideas on either (a) identifying the host or, (b) backing up a bit, being able to use the host's own Read-Host cmdlet to get a typed input from a user?






Check if a "Type" override a dynamic type

We are giving some repetitive jobs to a consultant company, we just have a few constraints that could not be checked by compilation, like a requirement to override a specific property in all class implementing a specific interface.


The property of the interface, which should be overrided in all classes has the following signature:



dynamic Definition{get;}


I found this stackoverflow question: How to find out if property is inherited from a base class or declared in derived?


Which is closed to my case, but in my case, the property is defined is inherited class and overrided in this one:



public class ClassA:IMyInterface
{
public virtual dynamic Definition{get{ /*return SomethingSpecificToClassA;*/}}
}

public class ClassB:ClassA
{
public override dynamic Definition{get{ /*return SomethingSpecificToClassB;*/}}
}


//The end goal is to know if ClassB has correctly overriden the property



bool overriden = typeof(ClassB)GetProperties(...).Any(p=>p.Name=="Definition");





Scala: get param default value: can't access `apply$default$i` inside companion object

I'm writing a macro that needs to get the default value of a constructor parameter. This answer shows this can be done by accessing the compiler-generated method apply$default$i on the companion object, where apply is the constructor's name and i is the 1-based parameter index.


However, this doesn't work if the macro is called from inside the companion object itself. Presumably the typechecking of the code in the companion object happens before the compiler generates the apply$default$i method.


This code works (whether written manually or generated by the macro):



case class C(i: Int = 1)
object C
def x: Int = C.apply$default$1


But this doesn't:



case class C(i: Int = 1)
object C {
def x: Int = C.apply$default$1
}


scalac complains that value apply$default$1 is not a member of object C.


I need to call the macro from the companion object because the macro defines an implicit typeclass instance.


I could generate code that will, at runtime, use reflection to access the apply$default$i method. But this is inelegant. If I know the compiler is going to generate a certain method, how can I access it in compiled code?






Weird static initialization in Java when using Reflection

Given the following code-snippet I get the output "B" and "error":



public class Test {

private static class A {
static final B c = new B();
}

private static class B extends A {
static final B c = A.c;
}

public static void main(String[] args) throws Exception {
for(Class<?> cls : Test.class.getDeclaredClasses()) {
if(cls.getDeclaredFields()[0].get(null) == null) {
System.out.println(cls.getSimpleName());
}
}
if(B.class.getDeclaredField("c").get(null) == null) {
System.out.println("error");
}
}

}


But it gets even more bizarre. If I comment-out the for-loop I get no output - so no error. Also if I access the field B.c directly without reflection before doing the reflection stuff the problem does not occur. Why is that so and how can I fix it?






Error NullPointerException trying to invoke a method passed

Main Activity there is:



public class Demo {

public void main() {
Class[] paramTypes = new Class[1];
parameterTypes[0] = Integer.Type;// tried also int.class;
Method method1 = Demo.class.getMethod("method1", parameterTypes);

OtherClass.askValue(this, new Demo(), method1, 100);
}

public void method1(int value) {
System.out.println(value);
}

}


In other Class in other java file:



public class OtherClass {

private Context ctx;
private Object obj;
private Method mtd;
private int ris;

public void askValue (Context context, Object object, Method method, int result) {
ctx = context;
obj = object;
mtd = method;
res = result;

AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle("title");
builder.setMessage("This is the message");
builder.setCancelable(false)
builder.setPositiveButton(R.string.yes, DIonClickPositive);
builder.setNegativeButton(R.string.no,new DInnClickNegative);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}

private DialogInterface.OnClickListener() DIonClickPositive = DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close

Object[] parameters = new Object[1];
parameters[0] = res;
try {
mtd.invoke(obj, parameters);
} catch (InvocationTargetException ite) {
Toast.makeText (ctx, "EXC ITE ["+ite.getCause()+"]", Toast.LENGTH_SHORT).show();
}

dialog.dismiss();
}
}

private DialogInterface.OnClickListener() DIonClickNegative = DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
dialog.dismiss();
}
}

}


When i confirm to the dialog (press positive button), it should invoke the method "method1", but instead it enter in the exception. The getCause() of that exception is "NullPointerException". In the android manual there is written it is caused when the first Object of the invoke is "null". I checked it, but it isn't null.



if (obj == null) Toast.make.Text(ctx, "OBJ NULL !!!", Toast.LENGTH_SHORT).show();


No toast shown, so it isn't null.


How can i resolve ?


Thanksss


PS: i used this example "[click here]", post of Blaise Doughan.






mardi 24 février 2015

C# Delegate and Events for Beginners

I am a beginner C# programmer just stepping into the advanced world of plugins.


What I have at the moment: I have a base architecture for plugins to provide GUIs, Functions, and classes and each instance of GUI, function and class can be accessed by other plugins. (For ex. if the state of one plugin (plugin a) changes because the user has changed then it can change the text in a label in plugin b to the new user name).


What I am trying to get working: In one word. Events. If plugin a has an event I want plugin b to be able to subscribe to it. I am using a generic event handler delegate but it doesn't want to subscribe.


Resources I have seen already: http://ift.tt/1D9LpT5 - Extremely useful


c# Plugin Event Handling


Firing events within a plug-in architecture vs single application


The issue is that most people are trying to subscribe to an event in a plugin from an application. I wish to subscribe one plugin to the event of a second plugin


My code at the moment:


Plugin 1 Events:



public class Events
{

public event tester testingevt;
public delegate void tester(object o, EventArgs e);

public void fireIt()
{
if (testingevt != null)
{
testingevt(this, null);
}
}
}


Plugin 2 (subscription):



public void onLoad()
{
object tempInstance = pf.getInstance("thisisaplugin", "Events");
Type t = tempInstance.GetType();
t.GetEvent("testingevt").AddEventHandler(tempInstance, new EventHandler(tester));
}


I have also seen various MSDN articles but none of them try to subscribe one plugin to another.


The code I am using came directly from the dreamincode.net link.


I have tried many different ways by creating delegate types, taking eventinfo variables to store the event and this was the closest I got to gathering it but the error this code throws is:



Object of type 'System.EventHandler' cannot be converted to type 'Test_Plugin_for_Server.Events+tester'



Please can anyone help me out?


Thanks in advance.






What is the equivalent of the "is" operator for reflected generic types?

Using the is operator in C# with generic types is straightforward:



if (new List<MyClass>()) is IEnumerable<MyClass>) {
// always branches
}


But what about when comparing types? I was hopeful that I could use Type.IsSubclassOf(Type type) here, but System.Collections.Generic.List<> implements System.Collections.Generic.IEnumerable<> -- It doesn't extend it. So I assume that's why the following happens:



var listType = typeof(List<MyClass>);
var enumerableType = typeof(IEnumerable<MyClass>);

if (listType.IsSubclassOf(enumerableType)) {
// NEVER branches
}


If I had an instance of my rvalue Type I could easily use Type.IsInstanceOfType(object o), but this point in the code is far removed from the instance from which the Type in question was reflected.


Am I missing something in the Type API? Am I forced to roll my own via an extension method?






Get property value to use within custom attribute

I have been looking for an example of how to get a property's value from within a custom attribute's code.


Example for illustration purposes only: We have a simple book class with only a name property. The name property has a custom attribute:



public class Book
{
[CustomAttribute1]
property Name { get; set; }
}


Within the custom attribute's code, I would like to get the value of the property on which the attribute has been decorated:



public class CustomAttribute1: Attribute
{
public CustomAttribute1()
{
//I would like to be able to get the book's name value here to print to the console:
// Thoughts?
Console.WriteLine(this.Value)
}
}


Of course, "this.Value" does not work. Any thoughts?






Using Reflection to Get All Static Properties in a Class As Objects VB.NET

I would like to start that I don't want a to hear about how expensive and terrible reflection is. That won't help—I have a very good reason to use reflection and that's not my question.


Specifically, I have a class within a class that contains several static properties of the same type.



Public Class Foo
Public Class Bar
Public Shared Property prop1 As New CustomClass()
Public Shared Property prop2 As New CustomClass()
Public Shared Property prop3 As New CustomClass()
End Class
End Class

Public Class CustomClass
Public Sub DoStuff()
End Sub
End Class


I'm looking to create a method in Foo that calls DoStuff on each of the properties contained within it. How can I do this? Here's the general idea of what I want to include in Foo, but I obviously can't convert PropertyInfo to CustomClass:



Private Sub Example()
For Each prop As PropertyInfo In GetType(Foo.Bar).GetProperties()
DirectCast(prop, CustomClass).DoStuff()
Next
End Sub


How can I get the static properties and cast them to CustomClass objects?






Reflecting Enumerations in Scala

How can I best reflect Enermations in Scala such that I can create Value objects from a string later?


For example:



object Num extends Enumeration {
val Aaa,Bbb,Ccc = Value
}
case class Boom( name:String, num:Num.Value )

def staticScan(
ctype:Type
) = {
ctype.typeSymbol match {
case s if(s.fullName == "scala.Enumeration.Value") =>
val owner = s.owner.asClass // Finds "scala.Enumeration"
// Now what?

// This is kinda awful, but it does work...
val erasedEnumClass = Class.forName(ctype.asInstanceOf[TypeRef].toString.replace(".Value","$"))
val enum = erasedEnumClass.getField(scala.reflect.NameTransformer.MODULE_INSTANCE_NAME).get(null).asInstanceOf[Enumeration]

enum
}
}

val enumThing = staticScan(currentMirror.classSymbol(Boom("Fred",Num.Aaa).getClass).typeSignature)
val newEnum = enumThing.withName("Bbb") // Creates Num.Value of Bbb


Is there a cleaner way to do this presuming static reflection? I may not always have an object available?


I've tried something like this but didn't work:



val ctor = owner.primaryConstructor
val maker = currentMirror.reflectClass(owner).reflectConstructor(ctor.asMethod)
...
maker.apply().asInstanceOf[Enumeration].withName("Bbb")





Go Reflect Method Call invalid memory address or nil pointer dereference

I'm trying to use reflect to call a method on a struct.


The code I have is dispersed, but everything relevant should be here;



// Begin new transaction, attach to new transaction service
transactionService := &models.TransactionService{}
transactionService.Begin()

// Transactioner interface type
transactionerType := reflect.TypeOf((*models.Transactioner)(nil)).Elem()

// Go through target controllers' models
// Attach transactionService to each model

val := reflect.ValueOf(c.AppController).Elem()
for i := 0; i < val.NumField(); i++ {
// For each field, check if it'
valueField := val.Field(i)

if valueField.Type().Implements(transactionerType) {
attachMethodValue := valueField.MethodByName("Attach")
args := []reflect.Value{reflect.ValueOf(transactionService)}
revel.INFO.Printf("%+v",attachMethodValue)
revel.INFO.Println(args)
attachMethodValue.Call(args)
}
}


...


The two print-statements near the end give the following output, followed by a panic



INFO 2015/02/24 21:01:12 gorp.go:122: Begun transaction
INFO 2015/02/24 21:01:12 init.go:79: <func(*models.TransactionService) Value>
INFO 2015/02/24 21:01:12 init.go:80: [<*models.TransactionService Value>]
ERROR 2015/02/24 21:01:12 panic.go:29: runtime error: invalid memory address or nil pointer dereference


As you can see, they don't seem to be nil values, which is why I'm confused about why I'm getting the panic.


Other code that might provide the contextual information.



type AppController struct {
*revel.Controller
}

type UserController struct {
AppController
UserModel *models.UserModel
}

type GorpModel struct {
transactionService *TransactionService
}

func (m *GorpModel) Attach(transactionService *TransactionService) {
m.transactionService = transactionService
revel.INFO.Println("Transactioner called!")
}

type Transactioner interface {
Attach(transactionService *TransactionService)
}

type TransactionService struct {
txn *gorp.Transaction
}

func (t *TransactionService) Begin() {
revel.INFO.Println("Begun transaction")
t.txn = BeginTransaction()
}


Any ideas on what the issue is?