Monday, September 1, 2014

How to find the length of a java.lang.String object without using any inbuilt String methods in and only in Java?

This may seem like an incredible challenge to be able to do this, because java.lang.String object only has method members that are public, and all field members are all private.
But it can be accomplished by using the java.lang.reflect and set the accessible flag for the String object.
Here is how:
import java.lang.reflect.Field;

public class GetStringLength{
 public static void main(String[] args)
  throws Exception{
  String t="test";
  Field f=String.class.getDeclaredField("value");
  f.setAccessible(true);
  System.out.println(((char[])f.get(t)).length);
 }
}
The output:
4
BUILD SUCCESSFUL (total time: 0 seconds)
As you can see no java.lang.String methods were used to get the length.

No comments:

Post a Comment