Lesson 7: Accessing Fields
Introduction
Accessing the field members of Java objects via proxy types is as easy as it is in pure Java.
Given a Java type like
public class DataType { public final static String STATIC_DATA = "test"; public int i; public Object obj; }
we can write the following C# code:
DataType dt = new DataType(); dt.i = 4; dt.i += 7; dt.obj = "string value"; Console.WriteLine( "{0}", DataType.STATIC_DATA );
There is of course a lot of heavy-lifting going on behind the scenes to make this happen. Java fields
translate to .NET properties with a getter and, if the field is not declared final
on the Java
side, a setter.
There is one crucial difference between Java and .NET: .NET does not permit static
members
in interfaces whereas Java uses this feature extensively to declare constants. To work around this issue,
interface proxy types have a nested Impl
type that exposes all static
members. To
access a static
interface member you write:
Console.WriteLine( "{0}", MyIfcType.Impl.MY_STATIC_DATA);
Patterns to Avoid
As you can see from the snippets above, this works remarkably well and is almost completely transparent to the developer. But if performance matters to you you should avoid accessing the same field multiple times if the value is not expected to change between invocations. Get the field value, assign it to a variable on the .NET side and then use that cached value. While we do our best to make the cross-language field access as inexpensive as possible, it never hurts to avoid unnecessary cross-language calls.