View Javadoc
1   package org.codehaus.plexus.languages.java.version;
2   
3   import java.io.ByteArrayInputStream;
4   import java.io.DataInputStream;
5   import java.io.IOException;
6   import java.io.UncheckedIOException;
7   
8   /*
9    * Licensed to the Apache Software Foundation (ASF) under one
10   * or more contributor license agreements.  See the NOTICE file
11   * distributed with this work for additional information
12   * regarding copyright ownership.  The ASF licenses this file
13   * to you under the Apache License, Version 2.0 (the
14   * "License"); you may not use this file except in compliance
15   * with the License.  You may obtain a copy of the License at
16   *
17   *   http://www.apache.org/licenses/LICENSE-2.0
18   *
19   * Unless required by applicable law or agreed to in writing,
20   * software distributed under the License is distributed on an
21   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
22   * KIND, either express or implied.  See the License for the
23   * specific language governing permissions and limitations
24   * under the License.
25   */
26  
27  /**
28   * This class is intented to be package-private and consumed by
29   * {@link JavaClassfileVersion}.
30   *
31   * @author Jorge Solórzano
32   */
33  final class JavaClassfileVersionParser {
34  
35      private JavaClassfileVersionParser() {}
36  
37      /**
38       * Reads the bytecode of a Java class file and returns the {@link JavaClassfileVersion}.
39       *
40       * @param in {@code byte[]} of the Java class file
41       * @return the {@link JavaClassfileVersion} of the input stream
42       */
43      public static JavaClassfileVersion of(byte[] bytes) {
44          try (final DataInputStream data = new DataInputStream(new ByteArrayInputStream(bytes))) {
45              if (0xCAFEBABE != data.readInt()) {
46                  throw new IOException("Invalid java class file header");
47              }
48              int minor = data.readUnsignedShort();
49              int major = data.readUnsignedShort();
50              return new JavaClassfileVersion(major, minor);
51          } catch (IOException ex) {
52              throw new UncheckedIOException(ex);
53          }
54      }
55  }