Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

Java inflections

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Transforms words (from singular to plural, from camelCase to under_score, etc.). I got bored of doing Real Work...
 * 
 * @author chuyeow
 */
public class Inflector {

    // Pfft, can't think of a better name, but this is needed to avoid the price of initializing the pattern on each call.
    private static final Pattern UNDERSCORE_PATTERN_1 = Pattern.compile("([A-Z]+)([A-Z][a-z])");
    private static final Pattern UNDERSCORE_PATTERN_2 = Pattern.compile("([a-z\\d])([A-Z])");

    private static List<RuleAndReplacement> plurals = new ArrayList<RuleAndReplacement>();
    private static List<RuleAndReplacement> singulars = new ArrayList<RuleAndReplacement>();
    private static List<String> uncountables = new ArrayList<String>();

    private static Inflector instance; // (Pseudo-)Singleton instance.

    private Inflector() {
        // Woo, you can't touch me.
        
        initialize();
    }
    
    private void initialize() {
        plural("$", "s");
        plural("s$", "s");
        plural("(ax|test)is$", "$1es");
        plural("(octop|vir)us$", "$1i");
        plural("(alias|status)$", "$1es");
        plural("(bu)s$", "$1es");
        plural("(buffal|tomat)o$", "$1oes");
        plural("([ti])um$", "$1a");
        plural("sis$", "ses");
        plural("(?:([^f])fe|([lr])f)$", "$1$2ves");
        plural("(hive)$", "$1s");
        plural("([^aeiouy]|qu)y$", "$1ies");
        plural("([^aeiouy]|qu)ies$", "$1y");
        plural("(x|ch|ss|sh)$", "$1es");
        plural("(matr|vert|ind)ix|ex$", "$1ices");
        plural("([m|l])ouse$", "$1ice");
        plural("(ox)$", "$1en");
        plural("(quiz)$", "$1zes");

        singular("s$", "");
        singular("(n)ews$", "$1ews");
        singular("([ti])a$", "$1um");
        singular("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis");
        singular("(^analy)ses$", "$1sis");
        singular("([^f])ves$", "$1fe");
        singular("(hive)s$", "$1");
        singular("(tive)s$", "$1");
        singular("([lr])ves$", "$1f");
        singular("([^aeiouy]|qu)ies$", "$1y");
        singular("(s)eries$", "$1eries");
        singular("(m)ovies$", "$1ovie");
        singular("(x|ch|ss|sh)es$", "$1");
        singular("([m|l])ice$", "$1ouse");
        singular("(bus)es$", "$1");
        singular("(o)es$", "$1");
        singular("(shoe)s$", "$1");
        singular("(cris|ax|test)es$", "$1is");
        singular("([octop|vir])i$", "$1us");
        singular("(alias|status)es$", "$1");
        singular("^(ox)en", "$1");
        singular("(vert|ind)ices$", "$1ex");
        singular("(matr)ices$", "$1ix");
        singular("(quiz)zes$", "$1");

        irregular("person", "people");
        irregular("man", "men");
        irregular("child", "children");
        irregular("sex", "sexes");
        irregular("move", "moves");

        uncountable(new String[] {"equipment", "information", "rice", "money", "species", "series", "fish", "sheep"});
    }

    public static Inflector getInstance() {
        if (instance == null) {
            instance = new Inflector();
        }
        return instance;
    }

    public String underscore(String camelCasedWord) {

        // Regexes in Java are fucking stupid...
        String underscoredWord = UNDERSCORE_PATTERN_1.matcher(camelCasedWord).replaceAll("$1_$2");
        underscoredWord = UNDERSCORE_PATTERN_2.matcher(underscoredWord).replaceAll("$1_$2");
        underscoredWord = underscoredWord.replace('-', '_').toLowerCase();

        return underscoredWord;
    }

    public String pluralize(String word) {
        if (uncountables.contains(word.toLowerCase())) {
            return word;
        }
        return replaceWithFirstRule(word, plurals);
    }

    public String singularize(String word) {
        if (uncountables.contains(word.toLowerCase())) {
            return word;
        }
        return replaceWithFirstRule(word, singulars);
    }

    private String replaceWithFirstRule(String word, List<RuleAndReplacement> ruleAndReplacements) {

        for (RuleAndReplacement rar : ruleAndReplacements) {
            String rule = rar.getRule();
            String replacement = rar.getReplacement();

            // Return if we find a match.
            Matcher matcher = Pattern.compile(rule, Pattern.CASE_INSENSITIVE).matcher(word);
            if (matcher.find()) {
                return matcher.replaceAll(replacement);
            }
        }
        return word;
    }

    public String tableize(String className) {
        return pluralize(underscore(className));
    }
    
    public String tableize(Class klass) {
        // Strip away package name - we only want the 'base' class name.
        String className = klass.getName().replace(klass.getPackage().getName()+".", "");
        return tableize(className);
    }

    public static void plural(String rule, String replacement) {
        plurals.add(0, new RuleAndReplacement(rule, replacement));
    }

    public static void singular(String rule, String replacement) {
        singulars.add(0, new RuleAndReplacement(rule, replacement));
    }

    public static void irregular(String singular, String plural) {
        plural(singular, plural);
        singular(plural, singular);
    }

    public static void uncountable(String... words) {
        for (String word : words) {
            uncountables.add(word);
        }
    }
}


// Ugh, no open structs in Java (not-natively at least).
class RuleAndReplacement {
    private String rule;
    private String replacement;
    public RuleAndReplacement(String rule, String replacement) {
        this.rule = rule;
        this.replacement = replacement;
    }
    public String getReplacement() {
        return replacement;
    }
    public void setReplacement(String replacement) {
        this.replacement = replacement;
    }
    public String getRule() {
        return rule;
    }
    public void setRule(String rule) {
        this.rule = rule;
    }
}

finds the file and line of executed code

module Kernel
  def which(&block)
    result = 'No ruby call has happen in the given block!'
    found = false
    set_trace_func lambda { |event, file, line, id, binding, classname|
      return unless event == 'call'
      result = "#{file}:#{line}: " unless found
      found = true
    }
    yield
    set_trace_func(nil)
    result
  end
end

# test
require 'yaml'
puts which { [].to_yaml }

2 + 2 = 5

Here is some very exciting Java code for printing 5.

import java.security.*;
import java.lang.reflect.*;
import java.util.*;

public class Test
{
    public static void main(String[] args) throws Exception
    {   
        AccessController.doPrivileged( new PrivilegedAction<Object>(){ public Object run(){try {
        Field field = Class.forName("java.lang.Integer$IntegerCache").getDeclaredFields()[0];
        field.setAccessible(true);

        Integer[] cache = (Integer[])field.get(null);
            
        cache[130] = 3;  
            
        Integer foo = 2;
 
        System.out.println(foo + 2); 
            
        return null;} catch(Exception e) { throw new RuntimeException(e); } } }); 
    }


}

Accessing private methods and fields of a Java class

This class uses reflection to enable you to invoke private methods on a class, or access its private fields. This can be useful for unit testing.

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import junit.framework.Assert;

/**
 * Provides access to private members in classes.
 */
public class PrivateAccessor {
	
  public static Object getPrivateField (Object o, String fieldName) {   
	 // Check we have valid arguments... 
    Assert.assertNotNull(o);
    Assert.assertNotNull(fieldName);
    
    // Go and find the private field... 
    final Field fields[] = o.getClass().getDeclaredFields();
    for (int i = 0; i < fields.length; ++i) {
      if (fieldName.equals(fields[i].getName())) {
        try {
          fields[i].setAccessible(true);
          return fields[i].get(o);
        } 
        catch (IllegalAccessException ex) {
          Assert.fail ("IllegalAccessException accessing " + fieldName);
        }
      }
    }
    Assert.fail ("Field '" + fieldName +"' not found");
    return null;
  }
  
  public static Object invokePrivateMethod (Object o, String methodName, Object[] params) {   
		 // Check we have valid arguments... 
	    Assert.assertNotNull(o);
	    Assert.assertNotNull(methodName);
	    Assert.assertNotNull(params);
	    
	    // Go and find the private method... 
	    final Method methods[] = o.getClass().getDeclaredMethods();
	    for (int i = 0; i < methods.length; ++i) {
	      if (methodName.equals(methods[i].getName())) {
	        try {
	          methods[i].setAccessible(true);
	          return methods[i].invoke(o, params);
	        } 
	        catch (IllegalAccessException ex) {
	          Assert.fail ("IllegalAccessException accessing " + methodName);
	        }
	        catch (InvocationTargetException ite) {
	        	Assert.fail ("InvocationTargetException accessing " + methodName);	        	
	        }
	      }
	    }
	    Assert.fail ("Method '" + methodName +"' not found");
	    return null;
	  }  
}

C# Reflection - Dealing with AmbiguousMatchException

C# code invoking a static method with reflection and dealing with an AmbiguousMatchException
Source: http://msdn2.microsoft.com/en-US/library/xthb9284.aspx


class Myambiguous {
    //The first overload is typed to an Int32
    public static void Mymethod (Int32 number){
       Console.Write("\n{0}", "I am from Int32 method");
    }

    //The second overload is typed to a string
    public static void Mymethod (string alpha) {
       Console.Write("\n{0}", "I am from a string.");
    }
    
    public static void Main() {
        try {
            //The following does not cause as exception
            Mymethod (2);  // goes to Mymethod (Int32)
            Mymethod ("3");   // goes to Mymethod (string)

            Type Mytype = Type.GetType("Myambiguous");

            MethodInfo Mymethodinfo32 = Mytype.GetMethod("Mymethod", new Type[]{typeof(Int32)});
            MethodInfo Mymethodinfostr = Mytype.GetMethod("Mymethod", new Type[]{typeof(System.String)});

            //Invoke a method, utilizing a Int32 integer
            Mymethodinfo32.Invoke(null, new Object[]{2});

            //Invoke the method utilizing a string
            Mymethodinfostr.Invoke(null, new Object[]{"1"});

            //The following line causes an ambiguious exception
            MethodInfo Mymethodinfo = Mytype.GetMethod("Mymethod");
        }  // end of try block
  
        catch(System.Reflection.AmbiguousMatchException theException) {
            Console.Write("\nAmbiguousMatchException message - {0}", theException.Message);
        }
        catch {
            Console.Write("\nError thrown");
        }
        return;
    }
}
 
 //This code produces the following output:
 //I am from Int32 method
 //I am from a string.
 //I am from Int32 method
 //I am from a string.
 //AmbiguousMatchException message - Ambiguous match found.

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS