简体   繁体   English

Java 中的泛型类

[英]Generic classes in Java

I have three Classes:我有三个班级:

  1. Generic Class that has 3 fields - a boolean, a String for a message, and a T result.具有 3 个字段的通用 Class - boolean、消息字符串和 T 结果。

  2. A second class that is having the function to multiply two numbers passed as method parameters.第二个 class 具有 function 以将作为方法参数传递的两个数字相乘。 The return type of this method is the generic class #1.此方法的返回类型是通用 class #1。

  3. The third Class is the same as the second, but instead, I am concatenating two string parameters.第三个 Class 与第二个相同,但我将两个字符串参数连接起来。

Question: How can my Generic class be used to display the result, the message, and the boolean for example, from Class #2?问:如何使用我的通用 class 来显示结果、消息和 boolean,例如来自 Class #2?

Baiscally, Class.result should display the multiplied numbers. Baiscally,Class.result 应该显示相乘的数字。

public class ClassOne<T> {

    boolean success;
    String errorMessage;
    T result;
}

public class ClassTwo {

public ClassOne<Long> multiplyNumbers(Long num1, Long num2) {
}

}

You'll need to instantiate it with the generic type您需要使用泛型类型对其进行实例化

public ClassOne<Long> multiplyNumbers(Long num1, Long num2) {
    ClassOne<Long> c = new ClassOne<>();
    try {
        Long multiplied = num1 * num2;
        c.setResult(multiplied);
    } catch (Exception e) {
        c.setError(e.getMessage());
    }
    return c;
}

For String concatenation, it would be the same, except I don't see how an exception could be thrown对于String连接,它是一样的,除了我看不到如何抛出异常

public ClassOne<String> concatStrings(String string1, String string2) {
    ClassOne<Long> c = new ClassOne<>();
    c.setResult(string1 + string2);
    return c;
}

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

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