3

为何 Java 从配置文件读取的时间参数会被强制认为是 Date 类型?设置 Object 类型会被...

 1 year ago
source link: https://www.v2ex.com/t/905904
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Java

为何 Java 从配置文件读取的时间参数会被强制认为是 Date 类型?设置 Object 类型会被强制转换成完整的 Date 格式?

  mylovesaber · 1 小时 35 分钟前 · 207 次点击

settings.yml 部分内容:

period:
  from: 2022-05-10
  to: 2023-01-01

如果我设置变量:

    private static String periodFrom;
    private static String periodTo;
    
    Yaml yaml = new Yaml();
    FileInputStream fileInputStream = new FileInputStream("settings.yml");
    HashMap yamlMap = yaml.load(fileInputStream);
    
    HashMap period = (HashMap) yamlMap.get("period");
    periodFrom = (String) period.get("from");
    periodTo = (String) period.get("to");
	System.out.println(periodFrom);

报错:Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to java.lang.String

也就是这里变量 periodFrom 和 periodTo 必须是 Date 或者 Object 这类范围更广的类型。java 为何会认定我设置的参数本身不是 String 而是 Date 呢?

如果我将 String 类型改成 Object 的话,sout 输出的是:Tue May 10 08:00:00 CST 2022 而不是我希望的 2022-05-10,这又是为什么呢?网上查了好像没什么头绪,还请赐教...

我希望的是读取这个日期参数,然后进行检查是否格式正确,如果正确,那么该日期将转换后(转换成 2017-01-01T00:00:00Z )用于从 gitlab 拉取 commit 信息

参考: https://github.com/gitlab4j/gitlab4j-api#commitsapi

// Get a list of commits associated with the specified branch that fall within the specified time window
// This uses the ISO8601 date utilities the in org.gitlab4j.api.utils.ISO8601 class
Date since = ISO8601.toDate("2017-01-01T00:00:00Z");
Date until = new Date(); // now
List<Commit> commits = gitLabApi.getCommitsApi().getCommits(1234, "new-feature", since, until);

xml 需要添加坐标:


    <repositories>
        <repository>
            <id>apache</id>
            <url>https://repo.maven.apache.org/maven2</url>
        </repository>
    </repositories>
    
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.33</version>
        </dependency>
    </dependencies>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK