java equivalent of c# typeof()

人走茶凉 提交于 2020-04-13 17:07:07

问题


I'm very new to java. Say I've a xml parser and I'd create object from it. In c# i'd do like:

parser p = new parser(typeof(myTargetObjectType));

In my parser class I need to know which object I'm making, so that i can throw exception if parsing is not possible. How to Do the same in jave? I mean how I can take arguments like typeof(myObject)


I understand every language has it's own way of doing something. I'm asking what's way in java


回答1:


Java has the Class class as the entry point for any reflection operation on Java types.

Instances of the class Class represent classes and interfaces in a running Java application

To get the type of an object, represented as a Class object, you can invoke the Object#getClass() method inherited by all reference types.

Returns the runtime class of this Object.

You cannot do this (invoke getClass()) with primitive types. However, primitive types also have an associated Class object. You can do

int.class

for instance.




回答2:


public class Main {
  public static void main(String[] args) {
    UnsupportedClass myObject = new UnsupportedClass();
    Parser parser = new Parser(myObject.getClass());
  }
}

class Parser {
  public Parser(Class<?> objectType) {
    if (UnsupportedClass.class.isAssignableFrom(objectType)) {
          throw new UnsupportedOperationException("Objects of type UnsupportedClass are not allowed");
    }
  }
}

class UnsupportedClass {}

Or since you have the instance of the object, this is easier:

Parser parser = new Parser(myObject);

public Parser(Object object) {
    if (object instanceof UnsupportedClass) {
          throw new UnsupportedOperationException("Objects of type UnsupportedClass are not allowed");
    }
}


来源:https://stackoverflow.com/questions/22774296/java-equivalent-of-c-sharp-typeof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!