java 相当于 c# typeof() [英] java equivalent of c# typeof()

查看:72
本文介绍了java 相当于 c# typeof()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 很陌生.假设我有一个 xml 解析器,我会从中创建对象.在 C# 中,我会这样做:

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

在我的解析器类中,我需要知道我正在创建哪个对象,以便在无法解析时抛出异常.如何在 java 中做同样的事情?我的意思是我如何接受像 typeof(myObject)

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)

我知道每种语言都有自己的做事方式.我在问java中的方法

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

推荐答案

Java 有 Class 类作为对 Java 类型进行任何反射操作的入口点.

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

类的实例 Class 代表类和接口运行 Java 应用程序

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

要获取对象的类型,表示为 Class 对象,您可以调用 Object#getClass() 方法被所有引用类型继承.

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

返回这个Object的运行时类.

您不能使用原始类型执行此操作(调用 getClass()).然而,原始类型也有一个关联的 Class 对象.你可以这样做

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

int.class

例如.

这篇关于java 相当于 c# typeof()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆