객체가 기본 유형인지 확인
나는이 Object[]
배열을, 나는 원시있는 사람을 찾기 위해 노력하고있다. 을 (를) 사용하려고했지만 Class.isPrimitive()
뭔가 잘못하고있는 것 같습니다.
int i = 3;
Object o = i;
System.out.println(o.getClass().getName() + ", " +
o.getClass().isPrimitive());
인쇄합니다 java.lang.Integer, false
.
올바른 방법이나 대안이 있습니까?
의 종류는 Object[]
않습니다 정말 원시적 수 없습니다 - 당신이 참조를 가지고 있기 때문에! 여기서의 유형은 i
is int
반면에서 참조하는 개체의 유형은 o
입니다 Integer
(자동 박싱으로 인해).
유형이 "기본 용 래퍼"인지 확인해야하는 것 같습니다. 이를 위해 표준 라이브러리에 내장 된 것이 없다고 생각하지만 코드화는 쉽습니다.
import java.util.*;
public class Test
{
public static void main(String[] args)
{
System.out.println(isWrapperType(String.class));
System.out.println(isWrapperType(Integer.class));
}
private static final Set<Class<?>> WRAPPER_TYPES = getWrapperTypes();
public static boolean isWrapperType(Class<?> clazz)
{
return WRAPPER_TYPES.contains(clazz);
}
private static Set<Class<?>> getWrapperTypes()
{
Set<Class<?>> ret = new HashSet<Class<?>>();
ret.add(Boolean.class);
ret.add(Character.class);
ret.add(Byte.class);
ret.add(Short.class);
ret.add(Integer.class);
ret.add(Long.class);
ret.add(Float.class);
ret.add(Double.class);
ret.add(Void.class);
return ret;
}
}
commons-lang ClassUtils
에는 관련 메서드가 있습니다.
새 버전은 다음과 같습니다.
boolean isPrimitiveOrWrapped =
ClassUtils.isPrimitiveOrWrapper(object.getClass());
이전 버전에는 기본 대응 wrapperToPrimitive(clazz)
을 반환하는 메서드가 있습니다.
boolean isPrimitiveOrWrapped =
clazz.isPrimitive() || ClassUtils.wrapperToPrimitive(clazz) != null;
Google의 Guava 라이브러리에는 클래스가 프리미티브의 래퍼 유형인지 확인 하는 프리미티브 유틸리티 가 있습니다 Primitives.isWrapperType(class)
.
Class.isPrimitive ()는 프리미티브에서 작동합니다.
간결한 코드를 좋아하는 사람들을 위해.
private static final Set<Class> WRAPPER_TYPES = new HashSet(Arrays.asList(
Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Void.class));
public static boolean isWrapperType(Class clazz) {
return WRAPPER_TYPES.contains(clazz);
}
Java 1.5 이상부터는 자동 박싱이라는 새로운 기능이 있습니다. 컴파일러가이 작업을 수행합니다. 기회를 발견하면 기본 유형을 적절한 래퍼 클래스로 변환합니다.
아마도 여기서 일어나는 일은
Object o = i;
컴파일러는이 문장을 다음과 같이 컴파일합니다.
Object o = Integer.valueOf(i);
이것은 자동 복싱입니다. 이것은 당신이 받고있는 출력을 설명 할 것입니다. Java 1.5 사양의이 페이지에서는 자동 박싱에 대해 자세히 설명합니다.
Integer
원시적 Class.isPrimitive()
이지 않고 거짓말이 아닙니다.
나는 이것이 자동 복싱 때문이라고 생각합니다 .
int i = 3;
Object o = i;
o.getClass().getName(); // prints Integer
이러한 특정 권투 클래스와 일치하는 유틸리티 메서드를 구현하고 특정 클래스가 기본 클래스인지 여부를 제공 할 수 있습니다.
public static boolean isWrapperType(Class<?> clazz) {
return clazz.equals(Boolean.class) ||
clazz.equals(Integer.class) ||
clazz.equals(Character.class) ||
clazz.equals(Byte.class) ||
clazz.equals(Short.class) ||
clazz.equals(Double.class) ||
clazz.equals(Long.class) ||
clazz.equals(Float.class);
}
자바의 자동 복싱을 처리해야합니다.
코드를 가져 가자
공개 수업 시험 { public static void main (String [] args) { int i = 3; 객체 o = i; 반환; } }test.class 클래스와 javap -c test를 받으면 생성 된 바이트 코드를 검사 할 수 있습니다.
"test.java"에서 컴파일 됨 공용 클래스 테스트는 java.lang.Object {를 확장합니다. 공개 테스트 (); 암호: 0 : aload_0 1 : invokespecial # 1; // 메소드 java / lang / Object. "":() V 4 : 반환보시다시피 Java 컴파일러가 추가되었습니다.public static void main (java.lang.String []); 암호: 0 : iconst_3 1 : istore_1 2 : iload_1 3 : invokestatic # 2; // Method java / lang / Integer.valueOf : (I) Ljava / lang / Integer; 6 : astore_2 7 : 반환
}
invokestatic # 2; // Method java / lang / Integer.valueOf : (I) Ljava / lang / Integer;int에서 새 Integer를 만든 다음 astore_2를 통해 o에 새 Object 를 저장 합니다.
public static boolean isValidType(Class<?> retType)
{
if (retType.isPrimitive() && retType != void.class) return true;
if (Number.class.isAssignableFrom(retType)) return true;
if (AbstractCode.class.isAssignableFrom(retType)) return true;
if (Boolean.class == retType) return true;
if (Character.class == retType) return true;
if (String.class == retType) return true;
if (Date.class.isAssignableFrom(retType)) return true;
if (byte[].class.isAssignableFrom(retType)) return true;
if (Enum.class.isAssignableFrom(retType)) return true;
return false;
}
isPrimitive가 true를 반환하는 것이 가능하다는 것을 알 수 있습니다 (거짓 이유를 보여주는 충분한 답변이 있기 때문에).
public class Main
{
public static void main(final String[] argv)
{
final Class clazz;
clazz = int.class;
System.out.println(clazz.isPrimitive());
}
}
메서드가 "Integer"가 아닌 "int"를 사용할 때 이것은 반영에서 중요합니다.
이 코드는 다음과 같이 작동합니다.
import java.lang.reflect.Method;
public class Main
{
public static void main(final String[] argv)
throws Exception
{
final Method method;
method = Main.class.getDeclaredMethod("foo", int.class);
}
public static void foo(final int x)
{
}
}
이 코드는 실패합니다 (메소드를 찾을 수 없음) :
import java.lang.reflect.Method;
public class Main
{
public static void main(final String[] argv)
throws Exception
{
final Method method;
method = Main.class.getDeclaredMethod("foo", Integer.class);
}
public static void foo(final int x)
{
}
}
여러 사람들이 이미 말했듯이 이것은 오토 박싱 때문 입니다.
당신은 수있는 객체의 클래스인지 여부를 확인하는 유틸리티 메소드를 작성 Integer
, Double
등,하지만이없는 오브젝트가 원시적를 오토 박싱에 의해 만들어 졌는지 여부를 알 수있는 방법이 ; 박스에 넣으면 명시 적으로 생성 된 객체처럼 보입니다.
따라서 배열에 오토 박싱 없이는 래퍼 클래스가 포함되지 않는다는 것을 확실히 알지 못하면 실제 솔루션이 없습니다.
primitve 래퍼 유형은이 값에 응답하지 않습니다. 이것은 프리미티브의 클래스 표현을위한 것이지만, 리플렉션을 제외하고는 너무 많이 사용한다고 생각할 수는 없습니다. 예를 들어
System.out.println(Integer.class.isPrimitive());
"false"를 인쇄하지만
public static void main (String args[]) throws Exception
{
Method m = Junk.class.getMethod( "a",null);
System.out.println( m.getReturnType().isPrimitive());
}
public static int a()
{
return 1;
}
"true"를 인쇄합니다.
나는 쇼에 늦었지만 필드를 테스트하는 경우 다음을 사용할 수 있습니다 getGenericType
.
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import org.junit.Test;
public class PrimitiveVsObjectTest {
private static final Collection<String> PRIMITIVE_TYPES =
new HashSet<>(Arrays.asList("byte", "short", "int", "long", "float", "double", "boolean", "char"));
private static boolean isPrimitive(Type type) {
return PRIMITIVE_TYPES.contains(type.getTypeName());
}
public int i1 = 34;
public Integer i2 = 34;
@Test
public void primitive_type() throws NoSuchFieldException, SecurityException {
Field i1Field = PrimitiveVsObjectTest.class.getField("i1");
Type genericType1 = i1Field.getGenericType();
assertEquals("int", genericType1.getTypeName());
assertNotEquals("java.lang.Integer", genericType1.getTypeName());
assertTrue(isPrimitive(genericType1));
}
@Test
public void object_type() throws NoSuchFieldException, SecurityException {
Field i2Field = PrimitiveVsObjectTest.class.getField("i2");
Type genericType2 = i2Field.getGenericType();
assertEquals("java.lang.Integer", genericType2.getTypeName());
assertNotEquals("int", genericType2.getTypeName());
assertFalse(isPrimitive(genericType2));
}
}
오라클 문서는 8 개 기본 유형을 나열합니다.
이것이 제가 생각할 수있는 가장 간단한 방법입니다. 래퍼 클래스는 java.lang
패키지 에만 있습니다. 래퍼 클래스를 제외하고의 다른 클래스 java.lang
에는 TYPE
. 이를 사용하여 클래스가 Wrapper 클래스인지 여부를 확인할 수 있습니다.
public static boolean isBoxingClass(Class<?> clazz)
{
String pack = clazz.getPackage().getName();
if(!"java.lang".equals(pack))
return false;
try
{
clazz.getField("TYPE");
}
catch (NoSuchFieldException e)
{
return false;
}
return true;
}
Spring http://static.springsource.org/spring/docs/3.0.x/javadoc-api/ 에서 BeanUtils를 확보 하십시오.
Probably the Apache variation (commons beans) has similar functionality.
you could determine if an object is wrapper type by beneath statements:
***objClass.isAssignableFrom(Number.class);***
and you could also determine a primitive object by using the isPrimitive() method
public class CheckPrimitve {
public static void main(String[] args) {
int i = 3;
Object o = i;
System.out.println(o.getClass().getSimpleName().equals("Integer"));
Field[] fields = o.getClass().getFields();
for(Field field:fields) {
System.out.println(field.getType());
}
}
}
Output:
true
int
int
class java.lang.Class
int
Ten years and this question is still current, at least for me... What's the nexus of 'isPrimitive' if it doesn't works with instances of primitives? I know the 'int.class' is primitive, so i don't need to ask this... Well, i made this:
import java.lang.reflect.*;
class Test{
public static void main(String[] args) throws Exception{
char x=3; boolean b=true; int i=2;
Object o= i;
Object name =o.getClass().getField("TYPE").get(o);
System.out.println(""+name);
}
}
This will return a String like "int", "char", "boolean", etc. All the eight primitives has a wrapper class wich has the "TYPE" field wich contains these values. The void type also does.
Another way, pratical use:
import java.util.*;
import java.lang.reflect.*;
class Test{
static void print(Object O){System.out.println(O);}
public static void main(String[] args) throws Exception{
List list2 = new ArrayList<Object>(List.of("word",2,3.0f,4.0,(char)65, a)); //where a= any user class instance.
//And see like this list simulates a tuple like in Pyhton, another lack i see in Java.
//But indeed, this kind of List<Object> is still better then a immutable tuple.
//And this was another of my doubts (tuples), and of other's people, as i've seen in my searchs at web.
ver(list2);
}
static void ver(List lis){
List prims = new ArrayList<String>(List.of("Boolean","Character","Byte","Double","Float","Integer","Long","Short"));
for(Object o: lis){
String s=o.getClass().getSimpleName();
print((prims.contains(s)?"Yes":"No"));
}
}
output: No Yes Yes Yes Yes No
For users of javapoet, there's also this way:
private boolean isBoxedPrimitive(Class<?> type) {
return TypeName.get(type).isBoxedPrimitive();
}
참고URL : https://stackoverflow.com/questions/709961/determining-if-an-object-is-of-primitive-type
'Programming' 카테고리의 다른 글
PHP에 AngularJS HTTP 게시 및 정의되지 않음 (0) | 2020.08.08 |
---|---|
jquery에서 닫으려면 메뉴 외부를 클릭하십시오. (0) | 2020.08.08 |
Sublime Text Editor에서 특정 확장자를 가진 파일을 숨기시겠습니까? (0) | 2020.08.08 |
명령 줄의 프로세서 / 코어 수 (0) | 2020.08.08 |
마지막 자식 선택기 사용 (0) | 2020.08.08 |