Dynamically find the class that represents a primitive Java type
The Spring framework contains a utility class ClassUtils which contains the static method forName. This method can be used for the exact purpose you described.
In case you don’t like to have a dependency on Spring: the source code of the method can be found e. g. here on their public repository. The class source code is licensed under the Apache 2.0 model.
Note however that the algorithm uses a hard-coded map of primitive types.
Edit: Thanks to commenters Dávid Horváth and Patrick for pointing out the broken link.
How do I check if a class represents a particular primitive type
This can be greatly simplified to:
intClass == int.class
This works because the Class
documentation says:
The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
Get Class of a primitive number type from a String
Is there a simple way to get Class of a primitive number type from String?
AFAIK ... No there isn't.
One reason is that many numeric strings can have multiple representational types; e.g. "42"
could represented as:
- a
byte
,short
,int
orlong
, - a
float
ordouble
, - wrapper types for the above,
- a
BigInteger
or aBigDecimal
, or ... - a
String
,StringBuilder
orStringBuffer
.
And the flip side is that a number like "25.8"
probably doesn't have a precise representation in any of the primitive types or their wrappers.
If there is (often) not single correct answer, it is not surprising that there is no general solution provided by the Java SE libraries, or any of the commonly user 3rd-party libraries.
How can I generically tell if a Java Class is a primitive type?
There is a method on the Class object called isPrimitive.
In JAVA, a primitive data type like int a CLASS or an OBJECT?
int
is a numeric type.int.class
is a class literal.
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type
void
, followed by a.
and the token class.
ClassLiteral
:
TypeName {[ ]} . class
NumericType {[ ]} . class
boolean {[ ]} . class
void . class
JLS 10 - 15.8.2. Class Literals
Moreover,
Class<Integer> intClass = int.class;
according to
The type of
p.class
, where p is the name of a primitive type (§4.2), isClass<B>
, whereB
is the type of an expression of typep
after boxing conversion (§5.1.7).JLS 10 - 15.8.2. Class Literals
How can I get a Class object form primitive?
For int
you normally do int.class
or Integer.TYPE
. Similarly for the other primitive types (e.g. double.class
).
Is it possible to obtain the Class object of a primitive type in Java when all you know is it's name?
You can't do that. Check out the reflection documentation. Go to the "Class.forName()" section and there, you can find a note:
This cannot be used for primitive types.
One option might be to create a method that will recognize the primitive types and return the matching class (i.e. Integer.class, Double.class, etc...)
Is there a way to compare a primitive type with its corresponding wrapper type?
You can use the static field TYPE
that every wrapper class has. (source)
for(int i=0; i<parameters.length; i++){
if(parameters[i].getType()==arrList.get(i).getClass().getField("TYPE").get(null)){
doSomething();
}
}
You could also compare the lowercase class names but you would have to handle int
and char
as special cases.
Alternatively you could create a Map<Class, Class>
between primitive classes and wrapper classes.
Can i make a class that behave like a primitive type?
The question might be a bit too broad, because one could argue quite extensively about what the word "behave" should mean. But to some extent, we can sort this out:
The shortest answer might be: No, this is not possible.
A slightly more elaborate answer might be: No, it is not yet possible to let a class (or more precisely: an object) behave like a primitive value.
The long answer:
There are efforts to achieve a behavior that might come close to what you're trying to accomplish. The relevant keyword here is Value Types.
Some resources:
- The original value types proposal by John Rose, Brian Goetz, and Guy Steele: http://cr.openjdk.java.net/~jrose/values/values-0.html
- The relevant JEP for Value Objects: http://openjdk.java.net/jeps/169
- The Wiki describing the goals and current state of value types: https://wiki.openjdk.java.net/display/valhalla/L-World+Value+Types
- The relevant mailing list: https://mail.openjdk.java.net/pipermail/valhalla-dev/
However, this is not supported in current versions of Java and the JVM, and it might still take a while until the details are sorted out.
Until then, there are some conceivable workarounds to achieve the desired goal.
The simplest solution is the one that you already proposed: You always return a new instance instead of modifying a given object.
The example that you showed in the question might not be the best to illustrate this, because the method getAdjacent
that you showed could in fact be a static
method. It does not use the instance that it is called on in any way.
Then you could always be sure that you received a new instance for each modification. Otherwise, imagine this code snippet:
Point a = new Point(1,2);
Point b = new Point(3,4);
a.add(b);
System.out.println(a); // What does this print?
Depending on the implementation of the add
method, the behavior might not be clear. If it was implemented like this:
public void add(Point other) {
this.x += other.x;
this.y += other.y;
}
then the point a
would be modified, and the output would be (4,6)
.
But if it was implemented like this
public Point add(Point other) {
return new Point(this.x+other.x, this.y+other.y);
}
then a
would remain unaffected, and the output would still be (1,2)
.
In general, making something like a Point
immutable basically enforces this style of programming. So you could make the variables x
and y
in your class final
, so that you could always be sure that the object cannot be modified after it was created:
public class Point {
// Note that these are FINAL:
private final int x;
private final int y;
public Point(int nx, int ny) {
this.x = nx;
this.y = ny;
}
...
}
There are some further design considerations for such a seemingly trivial thing like a Point
class (some of which I mentioned in this answer), but discussing them is beyond the scope of this answer.
Related Topics
Multiple Inheritance for an Anonymous Class
Httpclient 4.0.1 - How to Release Connection
Gson and Deserializing an Array of Objects with Arrays in It
Cannot Assign Requested Address Using Serversocket.Socketbind
Binding a List in @Requestparam
Java Fileinputstream Objectinputstream Reaches End of File Eof
Files.Walk(), Calculate Total Size
How to Change the Highlight Color of a Focused Jcombobox
How to Cast List<Object> to List<Myclass>
How to Get a Random Line of a Text File in Java
Spring Cron Expression for Every Day 1:01:Am
Can't Make Jackson and Lombok Work Together
Circular Dependency in Java Constructors