简体   繁体   English

java等效于c#typeof()

[英]java equivalent of c# typeof()

I'm very new to java. 我是Java的新手。 Say I've a xml parser and I'd create object from it. 假设我有一个xml解析器,然后从中创建对象。 In c# i'd do like: 在C#中,我会喜欢:

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? 如何在jave中做同样的事情? I mean how I can take arguments like typeof(myObject) 我的意思是我该如何接受像typeof(myObject)这样的参数


I understand every language has it's own way of doing something. 我了解每种语言都有自己的做事方式。 I'm asking what's way in java 我在问java中的方式

Java has the Class class as the entry point for any reflection operation on Java types. Java将Class类作为对Java类型进行任何反射操作的入口点。

Instances of the class Class represent classes and interfaces in a running Java application Class实例表示正在运行的Java应用程序中的类和接口

To get the type of an object, represented as a Class object, you can invoke the Object#getClass() method inherited by all reference types. 若要获取表示为Class对象的对象的类型,可以调用所有引用类型继承的Object#getClass()方法。

Returns the runtime class of this Object . 返回此Object的运行时类。

You cannot do this (invoke getClass() ) with primitive types. 您不能使用基本类型来执行此操作(调用getClass() )。 However, primitive types also have an associated Class object. 但是,基本类型也具有关联的Class对象。 You can do 你可以做

int.class

for instance. 例如。

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM