Reflection: Find the data type

Sunday, July 26th, 2009

from types import *
 
def what (x):
     if type(x) == IntType:
             print "This is an int."
     else:
             print "This is something else."
 
what(4)
what("4")

           
       

Set AssemblyTitle, AssemblyDescription, AssemblyConfiguration, AssemblyCompany, AssemblyProduct

Wednesday, July 15th, 2009

 

using System.Reflection;
using System.Windows.Forms;
   
[assembly: AssemblyTitle("title")]
[assembly: AssemblyDescription("code.")]
[assembly: AssemblyConfiguration("Retail")]
[assembly: AssemblyCompany("Inc.")]
[assembly: AssemblyProduct("C#")]
[assembly: AssemblyCopyright("Inc.")]
[assembly: AssemblyVersion("1.0.*")]
   
public class SimpleHelloWorld : Form
{
    public static void Main()
    {
        Application.Run(new SimpleHelloWorld());
    }
   
    public SimpleHelloWorld()
    {
        Text = "Hello, WindowsForms!";
    }
}

 

Demonstration of various method invocation issues

Saturday, July 11th, 2009

/*
 *     file: VariousMethodDemos.java
 *  package: oreilly.hcj.reflection
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
 ########## DO NOT EDIT ABOVE THIS LINE ########## */

import java.lang.reflect.Method;

/**
 * Demonstration of various method invocation issues.
 * 
 * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 * @version $Revision$
 */
public class VariousMethodDemos {
  /**
   * Run the demo.
   * 
   * @param args
   *          Command line arguments (ignored).
   */
  public static void main(final String[] args) {
    try {
      final Class[] ARG_TYPES = new Class[] { String.class };
      Object result = null;

      Method meth = Integer.class.getMethod("parseInt", ARG_TYPES);

      result = meth.invoke(null, new Object[] { new String("44") });
      System.out.println(result);

      result = meth.invoke(null, new Object[] { new String("Jonny") });
      System.out.println(result);
    } catch (final Exception ex) {
      ex.printStackTrace();
    }
  }
}

/* ########## End of File ########## */

 

Object Reflection: set value

Monday, July 6th, 2009

/* From http://java.sun.com/docs/books/tutorial/index.html */

/*
 * Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for NON-COMMERCIAL purposes and without fee is hereby granted
 * provided that this copyright notice appears in all copies. Please refer to
 * the file "copyright.html" for further important copyright and licensing
 * information.
 * 
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
 * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */

import java.awt.Rectangle;
import java.lang.reflect.Field;

public class SampleSet {

  public static void main(String[] args) {
    Rectangle r = new Rectangle(100, 20);
    System.out.println("original: " + r.toString());
    modifyWidth(r, new Integer(300));
    System.out.println("modified: " + r.toString());
  }

  static void modifyWidth(Rectangle r, Integer widthParam) {
    Field widthField;
    Integer widthValue;
    Class c = r.getClass();
    try {
      widthField = c.getField("width");
      widthField.set(r, widthParam);
    } catch (NoSuchFieldException e) {
      System.out.println(e);
    } catch (IllegalAccessException e) {
      System.out.println(e);
    }
  }
}
           
       

Get field type and generic type by field name

Saturday, June 27th, 2009

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.lang.reflect.Field;
import java.util.List;

public class FieldSpy<T> {
  public boolean[][] b = { { false, false }, { true, true } };
  public String name = "Alice";
  public List<Integer> list;
  public T val;

  public static void main(String… args) {
    try {
      Class<?> c = Class.forName("FieldSpy");
      Field f = c.getField("name");
      System.out.format("Type: %s%n", f.getType());
      System.out.format("GenericType: %s%n", f.getGenericType());

      // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    }
  }
}