在Java中实现通用的安全转换函数

huangapple go评论71阅读模式
英文:

Generalize safe cast functions in Java

问题

我有一个 Java 类,除了安全地将一些对象转换为它们预期的类并在转换失败时返回描述性错误消息外,什么都不做。它们都看起来像这样:

	public static RequirementId castToRequirementID(Object value) throws WrongObjectTypeException {
		Class<?> expectedClass = RequirementId.class;
		Class<?> actualClass = value.getClass();
		if(actualClass == expectedClass) {
			RequirementId requirementID = (RequirementId) value;
    		return requirementID;
		}
		String errorMessage = "Value was of wrong type";
		throw new WrongObjectTypeException(errorMessage, expectedClass, actualClass);
	}

	public static RequirementProjectInformation castToRequirementProjectInformation(Object value) throws WrongObjectTypeException {
		Class<?> expectedClass = RequirementProjectInformation.class;
		Class<?> actualClass = value.getClass();
		if(actualClass == expectedClass) {
			RequirementProjectInformation requirementProjectInformation = (RequirementProjectInformation) value;
    		return requirementProjectInformation;
		}
		String errorMessage = "Value was of wrong type";
		throw new WrongObjectTypeException(errorMessage, expectedClass, actualClass);
	}

正如你所看到的,这些函数基本上是相同的,只是需要在每个函数的第一行更改 expectedClass,以及在每个函数的第四行进行类型转换。这让我想以某种方式将其泛化,例如:

	public static MongoDB_ObjectAddress safelyCast(Object value, Class<?> expectedClass) throws WrongObjectTypeException {
		Class<?> actualClass = value.getClass();
		if(actualClass == expectedClass) {
			expectedClass castedObject = (expectedClass) value;
    		return castedObject;
		}
		String errorMessage = "Value was of wrong type";
		throw new WrongObjectTypeException(errorMessage, expectedClass, actualClass);
	}

然而,上述语句不起作用,因为我不能在声明和转换的地方使用 expectedClass 作为实际类名的替代。

有没有一些巧妙的方法可以做到这一点?还是在 Java 中根本不可能实现这一点?

英文:

I have a Java class that does nothing else than safely cast a number of objects to their expected classes, and returns a descriptive error message if the cast fails. They all look like this:

	public static RequirementId castToRequirementID(Object value) throws WrongObjectTypeException {
		Class&lt;?&gt; expectedClass = RequirementId.class;
		Class&lt;?&gt; actualClass = value.getClass();
		if(actualClass == expectedClass) {
			RequirementId requirementID = (RequirementId) value;
    		return requirementID;
		}
		String errorMessage = &quot;Value was of wrong type&quot;;
		throw new WrongObjectTypeException(errorMessage, expectedClass, actualClass);
	}

	public static RequirementProjectInformation castToRequirementProjectInformation(Object value) throws WrongObjectTypeException {
		Class&lt;?&gt; expectedClass = RequirementProjectInformation.class;
		Class&lt;?&gt; actualClass = value.getClass();
		if(actualClass == expectedClass) {
			RequirementProjectInformation requirementProjectInformation = (RequirementProjectInformation) value;
    		return requirementProjectInformation;
		}
		String errorMessage = &quot;Value was of wrong type&quot;;
		throw new WrongObjectTypeException(errorMessage, expectedClass, actualClass);
	}

As you can see, these functions are mostly identical, except for the fact that I need to change the expectedClass in the first line of each function, and the cast in the fourth line of each function. That makes me want to generalize this in some way, for example:

	public static MongoDB_ObjectAddress safelyCast(Object value, Class&lt;?&gt; expectedClass) throws WrongObjectTypeException {
		Class&lt;?&gt; actualClass = value.getClass();
		if(actualClass == expectedClass) {
			expectedClass castedObject = (expectedClass) value;
    		return castedObject;
		}
		String errorMessage = &quot;Value was of wrong type&quot;;
		throw new WrongObjectTypeException(errorMessage, expectedClass, actualClass);
	}

However, the above statement does not work since I can't use expectedClass in place of the actual class name in the declaration and the cast.

Is there some clever way to do this? Or is this simply impossible in Java?

答案1

得分: 2

你可以使用 Class.cast 方法:

public static <T> T safelyCast(Object value, Class<T> expectedClass) throws WrongObjectTypeException {
    if (expectedClass.isInstance(value)) {
        return expectedClass.cast(value);
    } else {
        String errorMessage = "Value was of wrong type";
        throw new WrongObjectTypeException(errorMessage, expectedClass, value.getClass());
    }
}

我必须说我并不太明白这个 WrongObjectTypeException 的意义,它并没有比你通常会得到的 ClassCastException 提供更多的信息。

英文:

You can use the Class.cast method:

public static &lt;T&gt; T safelyCast(Object value, Class&lt;T&gt; expectedClass) throws WrongObjectTypeException {
    if (expectedClass.isInstance(value)) {
        return expectedClass.cast(value);
    } else {
        String errorMessage = &quot;Value was of wrong type&quot;;
        throw new WrongObjectTypeException(errorMessage, expectedClass, value.getClass());
    }
}

I must say I don't see much point in this WrongObjectTypeException, it doesn't give you more information than the ClassCastException you would get normally.

huangapple
  • 本文由 发表于 2020年4月6日 20:02:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61059374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定