Change class name

Is it possible to change the name of the class obtained with: Foo.class.getName()

(or getSimpleName()

or getCanonicalName()

).

I know these methods are part java.lang.Class<T>

, the question itself is if there is a way to tell java.lang.Class<T>

what name I want to display for my class.

I know this "opens the door to tricky things" as this name is used by the reflection libraries to do "stuff" and "blah blah blah". however, I was wondering to be able to call it Foo.class.getSimpleName()

and get something like MyFoo

.

All this, of course, without string manipulation, which is the last alternative I have.

+3


source to share


2 answers


Search for src.zip in your JDK. Extract java/lang/Class.java

to some directory and change the method getSimpleName()

. For example, for example:

public String getSimpleName() {
    return "MyName"; // return MyName for any class
}

      

Compile it with javac (you will get a lot of warnings, ignore them). Remove any extra classes created as Class$1.class

, leaving only the file java/lang/Class.class

. Put it in the jar:

$ jar -c java >myclass.jar

      



Now add the bootstrap path to your new jar. For example, consider this test class:

public class Test {
   public static void main(String[] args) {
      System.out.println(Test.class.getSimpleName());
   }
}

$ java Test
Test

$ java -Xbootclasspath/p:myclass.jar Test
MyName

      

I don't even want to explain how dangerous it is. Also according to the Oracle binary license (optional term F), you cannot deploy your application this way.

+1


source


You can try Powermock , which, according to their home page, allows you to mock classes final

, although you need to use your own classloader to do so.



Other mocking frameworks that don't do byte code manipulation with custom classloaders like Mockito and Easymock can't handle the classes final

that java.lang.Class

are.

0


source







All Articles