如何创建一个Class,在其中我们可以直接赋值

How to create a Class, in which we can assign value directly

可能是标题误导了你。

String str ="abcd";

在上面的代码中,String 是一个 class,在不使用 new 的情况下,我们可以创建一个带有值的 object。现在我有一个 class Number.java,我必须在其中分配一些数字,如下所示。

Number no = 23;

如何创建这样的class。

我通常会说您应该使用运算符重载。但是这个功能在Java.

中是不存在的

看这里:Operator overloading in Java

你不能。

Java 编译器只是为您提供了一个语法快捷方式。

来自Java Tutorial

[...] a string literal [is] a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value

不能像字符串那样直接给对象赋值。

如果你真的想实现同样的事情,我建议你创建一个预定义初始化对象的工厂,并使用 Prototype pattern or FactoryMethod 模式从工厂获取所需的对象。

示例代码:

import java.util.concurrent.atomic.*;

public class PrototypeFactory
{
    public class NumberPrototype
    {
        public static final String THIRTY_TWO = "32";
        public static final String FORTY_ONE = "41";

    }

    private static java.util.Map<String , AtomicInteger> prototypes = new java.util.HashMap<String , AtomicInteger>();

    static
    {
        prototypes.put(NumberPrototype.THIRTY_TWO, new AtomicInteger(32));
        prototypes.put(NumberPrototype.FORTY_ONE, new AtomicInteger(43));

    }

    public static AtomicInteger getInstance( final String s) {
        //return (AtomicInteger)(prototypes.get(s)).clone();
        return ((AtomicInteger)prototypes.get(s));
    }
    public static void main(String args[]){
        System.out.println("Prototype.get(32):"+PrototypeFactory.getInstance(NumberPrototype.THIRTY_TWO));
    }
}

输出:

Prototype.get(32):32

实际上,由于自动装箱

,这种类型的分配确实适用于原始包装器 类
Integer n = 23;

你不能,因为原始值是 java 语言的一部分,如果你想让 class 变成 "initialized" 那样,你应该将它添加到java 解析或类似的东西。