How to get class of primitive types with Javassist?

In my program, I deal with classes and primitive types. If a program finds a class, it simply makes one of the following calls:

  • Class.forName(classname)
  • cc.toClass() where cc is an instance of CtClass

However, if it finds a primitive type, things get worse:

  • Class.forName not used; it cannot be used with primitive types.
  • cc.toClass() returns null

You can call the TYPE field from a wrapper class of primitive types, but how can I do this with reflection?

Here is my code:

 CtClass cc;//Obtained from caller code Class<?> classParam; if (cc.isprimitive()) { classParam= ?? // How can I get TYPE field value with reflection ? } else { String nomClasseParam = cc.getName(); if (nomClasseParam.startsWith("java")) { classeParam = Class.forName(nomClasseParam); } else { classeParam = cc.toClass(); } } 

Javassist 3.12.0.GA

EDIT: I posted the solution that I selected in the comments below. Anyway, I noted Tom's answer .

+6
source share
3 answers

It seems to me that you can use cc for your subclass CtPrimitiveType .

If you need a wrapper, you can use the getWrapperName method to get the class name of the corresponding wrapper. You can use Class.forName as usual to turn this name into a Class object. However, I don’t think you need a shell, so this does not help.

Instead, I think you want a getDescriptor followed by a painstakingly encoded switch statement:

 switch(descriptor) { case 'I': classParam = int.class; break; // etc } 

Something like this really should be in the javasist. But, as far as I see, this is not so.

+5
source

Based on the answers of Tom and Momo, here is the solution I came up with:

 CtClass cc; //Obtained from caller code Class<?> classParam; if (cc.isprimitive()) { classParam = Class.forName(((CtPrimitiveType)cc).getWrapperName()); classParam = (Class<?>)classParam.getDeclaredField("TYPE").get( classParam ); } else { String nomClasseParam = cc.getName(); if (nomClasseParam.startsWith("java")) { classeParam = Class.forName(nomClasseParam); } else { classeParam = cc.toClass(); } } 

I call the CtPrimitiveType#getWrapperName , and then I use the TYPE field to get a primitive type class. I also avoid writing switch statements.

Thanks for helping the guys.

+3
source

You can make Class.forName to wrap a primitive object (e.g. Integer for a primitive int). Java supports autoboxing, so you can exchange between an Object wrapper and a primitive copy.

I assume that you are using CtClass from JavaAssist. If cc is primitive, I think it will be type CtPrimitiveType (must be confirmed), in which case you can use getWrapperName () to get the wrapper class.

+1
source

Source: https://habr.com/ru/post/897142/


All Articles