RSS

Monthly Archives: October 2011

ExtJS and ASP.NET MVC 3: CRUD DataGrid

This short tutorial will walk though the implementation of DataGrid using ExtJS 3.3.1 andASP.NET MVC 3. In this tutorial I focus more on the integration of the front-end, so you will not find any database code. Whenever we deal with data we usually create, read/retrieve, update or delete them. ExtJS provides a great data grid component and the ability to perform CRUD operation with very little coding. I used JSON as data format in the example below.

ExtJS DataGridExtJS DataGrid

Let’s start with the server-side by developing the data model and controller.

Controller:

01 public class ContactController : Controller
02 {
03     //
04     // GET: /Contact/
05
06     public ActionResult Index()
07     {
08         return View();
09     }
10
11     public JsonResult Load()
12     {
13         var contact = new List<Contact> {
14             new Contact("Smith","95746325","smith@me.com"),
15             new Contact("Adam","87291034","adam@me.com"),
16             new Contact("Eve","98271345","eve@me.com"),
17             new Contact("Chun Li","81728312","chun.li@me.com")
18         };
19         return Json(new
20         {
21             total = contact.Count,
22             data = contact,
23         }, JsonRequestBehavior.AllowGet);
24     }
25
26     [HttpPost]
27     public JsonResult Create(List<Contact> data)
28     {
29         //insert Create code
30         return Json(new
31         {
32             data = new Contact(data[0].Name, data[0].Phone, data[0].Email),
33             success = true,
34             message = "Create method called successfully"
35         });
36     }
37
38     [HttpPost]
39     public JsonResult Update(List<Contact> data)
40     {
41         //insert Update code
42         return Json(new
43         {
44             success = true,
45             message = "Update method called successfully"
46         });
47     }
48
49     [HttpPost]
50     public JsonResult Delete(List<string> data)
51     {
52         //insert Delete code
53         return Json(new
54         {
55             success = true,
56             message = "Delete method called successfully"
57         });
58     }
59 }

Data Model:

01 public class Contact
02 {
03     public string Id { getset; }
04     public string Name { getset; }
05     public string Phone { getset; }
06     public string Email { getset; }
07
08     public Contact(string pName, string pPhone, string pEmail)
09     {
10         this.Id = System.Guid.NewGuid().ToString();
11         this.Name = pName;
12         this.Phone = pPhone;
13         this.Email = pEmail;
14     }
15
16     public Contact() { }
17 }

ExtJS:

Now, you move on to the view and work on the ExtJS. First, you define the record type which matches the server-side object.

01 var Contact = Ext.data.Record.create([
02     {
03         name: 'Id',
04         type: 'string'
05     }, {
06         name: 'Name',
07         type: 'string'
08     }, {
09         name: 'Phone',
10         type: 'string'
11     }, {
12         name: 'Email',
13         type: 'string'
14     }
15 ]);

Now you need to setup the Writer and Reader

01 var writer = new Ext.data.JsonWriter({
02     encode: false,
03     listful: true,
04     writeAllFields: true
05 });
06
07 var reader = new Ext.data.JsonReader({
08     totalProperty: 'total',
09     successProperty: 'success',
10     idProperty: 'Id',
11     root: 'data',
12     messageProperty: 'message'  // <-- New "messageProperty" meta-data
13 }, Contact);

Then, setup a proxy to define the connection to the controller.

1 var proxy = new Ext.data.HttpProxy({
2     api: {
3         read: '/Contact/Load',
4         create: '/Contact/Create',
5         update: '/Contact/Update',
6         destroy: '/Contact/Delete'
7     },
8     headers: { 'Content-Type''application/json; charset=UTF-8' }
9 });

Hooks the above components (reader, writer, proxy) to the store.

1 var store = new Ext.data.Store({
2     id: 'user',
3     proxy: proxy,
4     reader: reader,
5     writer: writer,
6     autoSave: false
7 });

Add the data grid declaration

01 var grid = new Ext.grid.GridPanel({
02     store: store,
03     columns: [
04         { header: "Name",
05             width: 170,
06             sortable: true,
07             dataIndex: 'Name',
08             editor: {
09                 xtype: 'textfield',
10                 allowBlank: false
11             }
12         },
13         { header: "Phone No.",
14             width: 160,
15             sortable: true,
16             dataIndex: 'Phone',
17             editor: {
18                 xtype: 'textfield',
19                 allowBlank: false
20             }
21         },
22         { header: "EMail",
23             width: 170,
24             sortable: true,
25             dataIndex: 'Email',
26             editor: {
27                 xtype: 'textfield',
28                 allowBlank: false
29             }
30         }
31     ],
32     plugins: [editor],
33     title: 'Contacts DataGrid',
34     height: 300,
35     width: 510,
36     tbar: [{
37         iconCls: 'icon-user-add',
38         text: 'Add Contact',
39         handler: function () {
40             var e = new Contact({
41                 Name: 'New Friend',
42                 Phone: '(65) 89182736',
43                 Email: 'new@google.com'
44             });
45             editor.stopEditing();
46             store.insert(0, e);
47             grid.getView().refresh();
48             grid.getSelectionModel().selectRow(0);
49             editor.startEditing(0);
50         }
51     }, {
52         ref: '../removeBtn',
53         iconCls: 'icon-user-delete',
54         text: 'Remove Contact',
55         handler: function () {
56             editor.stopEditing();
57             var s = grid.getSelectionModel().getSelections();
58             for (var i = 0, r; r = s[i]; i++) {
59                 store.remove(r);
60             }
61         }
62     }, {
63         iconCls: 'icon-user-save',
64         text: 'Save All Modifications',
65         handler: function () {
66             store.save();
67         }
68     }]
69 });

Some observations:

  • When submitting data as JSON, set the headers “Content-Type” to “application/json” in the proxy object and set the encoding to false in the JsonWriter. If not, it will be treated as form submission.
  • Since I set the auto save to false. DataGrid will submit list of contact when there are 2 or more changes, however it will send a single object when there is 1 change. In order to make it consistent to send as list, set list full to true in the JsonWriter.
  • ASP.NET MVC 3 able to recognize the JSON without additional coding.

If you want to see the complete source code, download it from here. Hope it’s useful. :)

Happy hacking!

Referenced by: http://myxaab.wordpress.com/2011/02/20/extjs-and-asp-net-mvc-3-crud-datagrid/

Advertisements
 
1 Comment

Posted by on October 23, 2011 in Javascript, Web Application

 

Nuget.Downloader package – Download a local NuGet repository using Nuget

by Jon Galloway

NuGet supports multiple feeds, running against either a server or a simple folder / fileshare. See Phil Haack’s post explaining both options for more information. I’m a big believer in running your own local NuGet feed for a lot of reasons – offline access, control over updates, and as an absolute must-have for demonstrations and training. I previously wrote up a NuGet Powershell script which pages through the NuGet OData feed and downloads local copies of the packages. It’s a little more complex than you’d guess, since the script needs to follow redirections and page links, plus I added in some options to skip downloads for features you’ve got, only grab the most popular X packages, etc.

I’d always assumed this would end up as a NuGet package, although the use case is a little out of the ordinary. The primary use case of NuGet is to add things (libraries, code, and content) to an existing application, and this NuGet package doesn’t work at the project level at all. But, it’s just so handy – and there had been enough requests for it – that I couldn’t help myself.

I’d actually started on this when Eric Hexter mentioned that he was working on it as well, so I merged what he’d done, removed all the affiliate ad codes he’d snuck in, and uploaded it yesterday. So, here’s NuGet.Downloader.

2011-03-10 15h46_44

 

  PM> Install-Package Ext.NET

 

How to use it

  1. Open a project in Visual Studio (it doesn’t matter which – if you try to install a package outside of a solution, you’ll get slapped down with “The current environment doesn’t have a solution open”).
  2. Open the Package Manager console (View / Other Windows / Package Manager Console).
  3. Type “install-package NuGet.Downloader” – you should see “Successfully installed ‘Nuget.Downloader 1.0.0.5’.” (with whatever the current version number is).
  4. This adds a new commend to the Package Manager console, Download-Packages. You can run it without any parameters, which will grab the top 500 most popular NuGet packages and drop them in a new LocalNuGet folder inside your My Documents folder.
  5. If desired, uninstall the package using Uninstall-Package.

Parameter options:

  • feedBaseUrl (default: official NuGet package feed, following redirections) – you can point this at a corporate NuGet server or some other location
  • latest (default: $true) – when true, only grabs the latest version of each package
  • overwrite (default: $false) – when true, downloads and overwrites all packages regardless of whether you already have a copy
  • top (default: 500) – number of packages to download, ordered by package popularity. If $null, downloads all packages; if 1 it would download the most popular package
  • destinationDirectory – (default: %HOMEPATH%\Documents\NuGetLocal) full path to the directory you’d like the packages downloaded to. Note: I changed this from LocalNuGet in the Powershell to NuGetLocal in the package, as I thought it made more sense

Example – downloading the top 10 most popular packages with overwrite option, then removing the package:

PM> Install-Package NuGet.Downloader
Successfully installed 'Nuget.Downloader 1.0.0.5'.   PM> Download-Packages -top 10 -overwrite $true
Downloading latest 10 packages (by download count)
downloading from http://packages.nuget.org/v1/FeedService.svc/Packages?$filter=IsLatestVersion eq true&$orderby=DownloadCount desc&$top=10
Complete. Local packages saved to C:\Users\Jon\Documents\NuGetLocal
PM> Uninstall-Package NuGet.Downloader
Successfully uninstalled 'Nuget.Downloader 1.0.0.5'.

PM>

Hope it helps you out, and please let me know how I can make it better.

Referenced by: http://weblogs.asp.net/jgalloway/archive/2011/03/10/nuget-downloader-package-download-a-local-nuget-repository-using-nuget.aspx

 
Leave a comment

Posted by on October 22, 2011 in C#

 

Windows Service Application

How to create a setup project for a window service application in Visual Studio C#

Requirement

  • Microsoft Windows 200/XP/Server 2003/Vista/Seven with .NET Framework installed.
  • Microsoft Visual Studio .NET 2005/2008

Create a Windows Service Project

  1. Start Microsoft Visual Studio
  2. On the File menu, point to New, and Click on Project.
  3. Click Visual C# Projects under Project Types, and then click Windows Service under Templates.

Use a Compiled Setup Project to Install the Windows Service

 
Leave a comment

Posted by on October 15, 2011 in General

 

Generic Singleton Class for Java

class singleton<T> {
    private static final singleton<?> instance = new singleton<Object>();
    private singleton() {}
    T variable;  

    public static singleton<?> getInstance() {
        return instance;
    }
}   
void test() {
    singleton<String> singletonString = (singleton<String>)singleton.getInstance();
    String s = singletonString.variable;
    singleton<Integer> singletonInteger = (singleton<Integer>)singleton.getInstance();
    Integer i = singletonInteger.variable;
} 

Referenced by: http://www.coderanch.com/t/470696/java/java/Generic-Singleton-Class

 
Leave a comment

Posted by on October 15, 2011 in Java Pro

 

Reset AutoIncrement in SqlServer after Delete

Issue the following command to reseed mytable to start at 1:

DBCC CHECKIDENT (mytable, RESEED, 1)

Read about it in the Books on Line (BOL, SQL help). Also be careful that you don’t have records higher than the seed you are setting.

Referenced by: http://stackoverflow.com/questions/510121/reset-autoincrement-in-sqlserver-after-delete

 
Leave a comment

Posted by on October 15, 2011 in SQL Server

 

Java Reflection: Private Fields and Methods

By Jakob Jenkov

Despite the common belief it is actually possible to access private fields and methods of other classes via Java Reflection. It is not even that difficult. This can be very handy during unit testing. This text will show you how.

Note: This only works when running the code as a standalone Java application, like you do with unit tests and regular applications. If you try to do this inside a Java Applet, you will need to fiddle around with the SecurityManager. But, since that is not something you need to do very often, it is left out of this text so far.

Here is a list of the topics covered in this text:

  1. Accessing Private Fields
  2. Accessing Private Methods

Accessing Private Fields

To access a private field you will need to call the Class.getDeclaredField(String name) orClass.getDeclaredFields() method. The methods Class.getField(String name) andClass.getFields() methods only return public fields, so they won’t work. Here is a simple example of a class with a private field, and below that the code to access that field via Java Reflection:

public class PrivateObject {

  private String privateString = null;

  public PrivateObject(String privateString) {
    this.privateString = privateString;
  }
}

PrivateObject privateObject = new PrivateObject("The Private Value");

Field privateStringField = PrivateObject.class.
            getDeclaredField("privateString");

privateStringField.setAccessible(true);

String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);

This code example will print out the text “fieldValue = The Private Value”, which is the value of the private field privateString of the PrivateObject instance created at the beginning of the code sample.

Notice the use of the method PrivateObject.class.getDeclaredField("privateString"). It is this method call that returns the private field. This method only returns fields declared in that particular class, not fields declared in any superclasses.

Notice the line in bold too. By calling Field.setAcessible(true) you turn off the access checks for this particular Field instance, for reflection only. Now you can access it even if it is private, protected or package scope, even if the caller is not part of those scopes. You still can’t access the field using normal code. The compiler won’t allow it.

Accessing Private Methods

To access a private method you will need to call the Class.getDeclaredMethod(String name, Class[] parameterTypes) or Class.getDeclaredMethods() method. The methodsClass.getMethod(String name, Class[] parameterTypes) and Class.getMethods()methods only return public methods, so they won’t work. Here is a simple example of a class with a private method, and below that the code to access that method via Java Reflection:

public class PrivateObject {

  private String privateString = null;

  public PrivateObject(String privateString) {
    this.privateString = privateString;
  }

  private String getPrivateString(){
    return this.privateString;
  }
}

PrivateObject privateObject = new PrivateObject("The Private Value");

Method privateStringMethod = PrivateObject.class.
        getDeclaredMethod("getPrivateString", null);

privateStringMethod.setAccessible(true);

String returnValue = (String)
        privateStringMethod.invoke(privateObject, null);

System.out.println("returnValue = " + returnValue);

This code example will print out the text “returnValue = The Private Value”, which is the value returned by the method getPrivateString() when invoked on the PrivateObject instance created at the beginning of the code sample.

Notice the use of the methodPrivateObject.class.getDeclaredMethod("privateString"). It is this method call that returns the private method. This method only returns methods declared in that particular class, not methods declared in any superclasses.

Notice the line in bold too. By calling Method.setAcessible(true) you turn off the access checks for this particular Method instance, for reflection only. Now you can access it even if it is private, protected or package scope, even if the caller is not part of those scopes. You still can’t access the method using normal code. The compiler won’t allow it.

 

Referenced by: http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html

 
Leave a comment

Posted by on October 12, 2011 in Java Pro

 

Using Java Reflection

By Glen McCluskey
January 1998

 

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or “introspect” upon itself, and manipulate internal properties of the program. For example, it’s possible for a Java class to obtain the names of all its members and display them.

The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn’t exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions defined within that program.

One tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool. The tool uses reflection to obtain the properties of Java components (classes) as they are dynamically loaded.

A Simple Example

To see how reflection works, consider this simple example:

   import java.lang.reflect.*;

   public class DumpMethods {
      public static void main(String args[])
      {
         try {
            Class c = Class.forName(args[0]);
            Method m[] = c.getDeclaredMethods();
            for (int i = 0; i < m.length; i++)
            System.out.println(m[i].toString());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

 

For an invocation of:

  java DumpMethods java.util.Stack

the output is:

  public java.lang.Object java.util.Stack.push(
    java.lang.Object)
   public synchronized 
     java.lang.Object java.util.Stack.pop()
   public synchronized
      java.lang.Object java.util.Stack.peek()
   public boolean java.util.Stack.empty()
   public synchronized 
     int java.util.Stack.search(java.lang.Object)

 

That is, the method names of class java.util.Stack are listed, along with their fully qualified parameter and return types.

This program loads the specified class using class.forName, and then calls getDeclaredMethods to retrieve the list of methods defined in the class. java.lang.reflect.Method is a class representing a single class method.

Setting Up to Use Reflection

The reflection classes, such as Method, are found in java.lang.reflect. There are three steps that must be followed to use these classes. The first step is to obtain a java.lang.Class object for the class that you want to manipulate. java.lang.Class is used to represent classes and interfaces in a running Java program.

One way of obtaining a Class object is to say:

   Class c = Class.forName("java.lang.String");

to get the Class object for String. Another approach is to use:

   Class c = int.class;

or

  Class c = Integer.TYPE;

to obtain Class information on fundamental types. The latter approach accesses the predefined TYPE field of the wrapper (such as Integer) for the fundamental type.

The second step is to call a method such as getDeclaredMethods, to get a list of all the methods declared by the class.

Once this information is in hand, then the third step is to use the reflection API to manipulate the information. For example, the sequence:

   Class c = Class.forName("java.lang.String");
   Method m[] = c.getDeclaredMethods();
   System.out.println(m[0].toString());

will display a textual representation of the first method declared in String.

In the examples below, the three steps are combined to present self contained illustrations of how to tackle specific applications using reflection.

Simulating the instanceof Operator

Once Class information is in hand, often the next step is to ask basic questions about the Class object. For example, the Class.isInstance method can be used to simulate the instanceofoperator:

   class A {}

   public class instance1 {
      public static void main(String args[])
      {
         try {
            Class cls = Class.forName("A");
            boolean b1 
              = cls.isInstance(new Integer(37));
            System.out.println(b1);
            boolean b2 = cls.isInstance(new A());
            System.out.println(b2);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

In this example, a Class object for A is created, and then class instance objects are checked to see whether they are instances of AInteger(37) is not, but new A() is.

Finding Out About Methods of a Class

One of the most valuable and basic uses of reflection is to find out what methods are defined within a class. To do this the following code can be used:

   import java.lang.reflect.*;

   public class method1 {
      private int f1(
       Object p, int x) throws NullPointerException
      {
         if (p == null)
            throw new NullPointerException();
         return x;
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method1");

            Method methlist[] 
              = cls.getDeclaredMethods();
            for (int i = 0; i < methlist.length;
               i++) {  
               Method m = methlist[i];
               System.out.println("name 
                 = " + m.getName());
               System.out.println("decl class = " +
                              m.getDeclaringClass());
               Class pvec[] = m.getParameterTypes();
               for (int j = 0; j < pvec.length; j++)
                  System.out.println("
                   param #" + j + " " + pvec[j]);
               Class evec[] = m.getExceptionTypes();
               for (int j = 0; j < evec.length; j++)
                  System.out.println("exc #" + j 
                    + " " + evec[j]);
               System.out.println("return type = " +
                                  m.getReturnType());
               System.out.println("-----");
            }
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

The program first gets the Class description for method1, and then calls getDeclaredMethods to retrieve a list of Method objects, one for each method defined in the class. These include public, protected, package, and private methods. If you use getMethods in the program instead of getDeclaredMethods, you can also obtain information for inherited methods.

Once a list of the Method objects has been obtained, it’s simply a matter of displaying the information on parameter types, exception types, and the return type for each method. Each of these types, whether they are fundamental or class types, is in turn represented by a Class descriptor.

The output of the program is:

  name = f1
   decl class = class method1
   param #0 class java.lang.Object
   param #1 int
   exc #0 class java.lang.NullPointerException
   return type = int
   -----
   name = main
   decl class = class method1
   param #0 class [Ljava.lang.String;
   return type = void
   -----

 

Obtaining Information About Constructors

A similar approach is used to find out about the constructors of a class. For example:

 import java.lang.reflect.*;

   public class constructor1 {
      public constructor1()
      {
      }

      protected constructor1(int i, double d)
      {
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("constructor1");

           Constructor ctorlist[]
               = cls.getDeclaredConstructors();
         for (int i = 0; i < ctorlist.length; i++) {
               Constructor ct = ctorlist[i];
               System.out.println("name 
                 = " + ct.getName());
               System.out.println("decl class = " +
                            ct.getDeclaringClass());
               Class pvec[] = ct.getParameterTypes();
               for (int j = 0; j < pvec.length; j++)
                  System.out.println("param #" 
                     + j + " " + pvec[j]);
               Class evec[] = ct.getExceptionTypes();
               for (int j = 0; j < evec.length; j++)
                  System.out.println(
                    "exc #" + j + " " + evec[j]);
               System.out.println("-----");
            }
          }
          catch (Throwable e) {
             System.err.println(e);
          }
      }
   }

There is no return-type information retrieved in this example, because constructors don’t really have a true return type.

When this program is run, the output is:

   name = constructor1
   decl class = class constructor1
   -----
   name = constructor1
   decl class = class constructor1
   param #0 int
   param #1 double
   -----

 

Finding Out About Class Fields

It’s also possible to find out which data fields are defined in a class. To do this, the following code can be used:

   import java.lang.reflect.*;

   public class field1 {
      private double d;
      public static final int i = 37;
      String s = "testing";

      public static void main(String args[])
      {
         try {
            Class cls = Class.forName("field1");

            Field fieldlist[] 
              = cls.getDeclaredFields();
            for (int i 
              = 0; i < fieldlist.length; i++) {
               Field fld = fieldlist[i];
               System.out.println("name
                  = " + fld.getName());
               System.out.println("decl class = " +
                           fld.getDeclaringClass());
               System.out.println("type
                  = " + fld.getType());
               int mod = fld.getModifiers();
               System.out.println("modifiers = " +
                          Modifier.toString(mod));
               System.out.println("-----");
            }
          }
          catch (Throwable e) {
             System.err.println(e);
          }
       }
   }

This example is similar to the previous ones. One new feature is the use of Modifier. This is a reflection class that represents the modifiers found on a field member, for example “private int“. The modifiers themselves are represented by an integer, and Modifier.toString is used to return a string representation in the “official” declaration order (such as “static” before “final“). The output of the program is:

  name = d
   decl class = class field1
   type = double
   modifiers = private
   -----
   name = i
   decl class = class field1
   type = int
   modifiers = public static final
   -----
   name = s
   decl class = class field1
   type = class java.lang.String
   modifiers =
   -----

As with methods, it’s possible to obtain information about just the fields declared in a class (getDeclaredFields), or to also get information about fields defined in superclasses (getFields).

Invoking Methods by Name

So far the examples that have been presented all relate to obtaining class information. But it’s also possible to use reflection in other ways, for example to invoke a method of a specified name.

To see how this works, consider the following example:

   import java.lang.reflect.*;

   public class method2 {
      public int add(int a, int b)
      {
         return a + b;
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Method meth = cls.getMethod(
              "add", partypes);
            method2 methobj = new method2();
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj 
              = meth.invoke(methobj, arglist);
            Integer retval = (Integer)retobj;
            System.out.println(retval.intValue());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

Suppose that a program wants to invoke the add method, but doesn’t know this until execution time. That is, the name of the method is specified during execution (this might be done by a JavaBeans development environment, for example). The above program shows a way of doing this.

getMethod is used to find a method in the class that has two integer parameter types and that has the appropriate name. Once this method has been found and captured into a Method object, it is invoked upon an object instance of the appropriate type. To invoke a method, a parameter list must be constructed, with the fundamental integer values 37 and 47 wrapped in Integer objects. The return value (84) is also wrapped in an Integer object.

Creating New Objects

There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction). So the nearest equivalent to the previous example is to say:

   import java.lang.reflect.*;

   public class constructor2 {
      public constructor2()
      {
      }

      public constructor2(int a, int b)
      {
         System.out.println(
           "a = " + a + " b = " + b);
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("constructor2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Constructor ct 
              = cls.getConstructor(partypes);
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj = ct.newInstance(arglist);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

which finds a constructor that handles the specified parameter types and invokes it, to create a new instance of the object. The value of this approach is that it’s purely dynamic, with constructor lookup and invocation at execution time, rather than at compilation time.

Changing Values of Fields

Another use of reflection is to change the values of data fields in objects. The value of this is again derived from the dynamic nature of reflection, where a field can be looked up by name in an executing program and then have its value changed. This is illustrated by the following example:

   import java.lang.reflect.*;

   public class field2 {
      public double d;

      public static void main(String args[])
      {
         try {
            Class cls = Class.forName("field2");
            Field fld = cls.getField("d");
            field2 f2obj = new field2();
            System.out.println("d = " + f2obj.d);
            fld.setDouble(f2obj, 12.34);
            System.out.println("d = " + f2obj.d);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

In this example, the d field has its value set to 12.34.

Using Arrays

One final use of reflection is in creating and manipulating arrays. Arrays in the Java language are a specialized type of class, and an array reference can be assigned to an Object reference.

To see how arrays work, consider the following example:

   import java.lang.reflect.*;

   public class array1 {
      public static void main(String args[])
      {
         try {
            Class cls = Class.forName(
              "java.lang.String");
            Object arr = Array.newInstance(cls, 10);
            Array.set(arr, 5, "this is a test");
            String s = (String)Array.get(arr, 5);
            System.out.println(s);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

This example creates a 10-long array of Strings, and then sets location 5 in the array to a string value. The value is retrieved and displayed.

A more complex manipulation of arrays is illustrated by the following code:

   import java.lang.reflect.*;

   public class array2 {
      public static void main(String args[])
      {
         int dims[] = new int[]{5, 10, 15};
         Object arr 
           = Array.newInstance(Integer.TYPE, dims);

         Object arrobj = Array.get(arr, 3);
         Class cls = 
           arrobj.getClass().getComponentType();
         System.out.println(cls);
         arrobj = Array.get(arrobj, 5);
         Array.setInt(arrobj, 10, 37);

         int arrcast[][][] = (int[][][])arr;
         System.out.println(arrcast[3][5][10]);
      }
   }

This example creates a 5 x 10 x 15 array of ints, and then proceeds to set location [3][5][10] in the array to the value 37. Note here that a multi-dimensional array is actually an array of arrays, so that, for example, after the first Array.get, the result in arrobj is a 10 x 15 array. This is peeled back once again to obtain a 15-long array, and the 10th slot in that array is set using Array.setInt.

Note that the type of array that is created is dynamic, and does not have to be known at compile time.

Summary

Java reflection is useful because it supports dynamic retrieval of information about classes and data structures by name, and allows for their manipulation within an executing Java program. This feature is extremely powerful and has no equivalent in other conventional languages such as C, C++, Fortran, or Pascal. Coffecup Logo

Glen McCluskey has focused on programming languages since 1988. He consults in the areas of Java and C++ performance, testing, and technical documentation.

 

Referenced by: http://java.sun.com/developer/technicalArticles/ALT/Reflection/

 
Leave a comment

Posted by on October 11, 2011 in Java Pro