Java class to classic

Как декомпилировать класс на Java

Список декомпиляторов Java и класс Java для декомпиляции в Eclipse IDE, IntelliJ IDEA и командной строке.

В этой статье показано, как декомпилировать класс Java в среде IDE Eclipse, IntelliJ IDEA и командной строке.

1. Декомпиляторы Java

Декомпилятор Java может конвертировать .class файлы возвращаются в исходный код .java файлы или преобразуют байт-код программы в исходный код. Ниже приведены некоторые из декомпиляторов Java:

  1. Цветок папоротника – встроенный декомпилятор Java IntelliJ IDEA.
  2. Проект JD – еще один быстрый декомпилятор Java, инструмент с графическим интерфейсом.
  3. Procyon – вдохновлен .NET ИЛСпи и Моно. Сесил.
  4. CFR – другой декомпилятор java, полностью написанный на Java 6, декомпилирует современные функции Java до Java 14.
  5. Jad – больше не поддерживается, закрытый исходный код.

2. Декомпилируйте класс Java в среде IDE Eclipse

В Eclipse IDE мы можем использовать Расширенный декомпилятор классов плагин для декомпиляции файлов классов Java без прямого исходного кода.

2.1 Выберите Справка -> Eclipse Marketplace. для поиска и установки Расширенного декомпилятора классов плагина.

2.2 Выберите Окно -> Настройки -> Общие -> Редакторы -> Ассоциации файлов , настройте *.класс без источника по умолчанию на Средство просмотра декомпилятора классов .

Сейчас , нажмите на класс или методы, нажмите F3 , и плагин автоматически декомпилирует класс Java.

Читайте также:  Php ini root directory

Примечание Для получения более подробной информации об установке и настройке Расширенного декомпилятора классов плагина, посетите этот декомпилятор Java в Eclipse IDE .

3. Декомпилируйте класс Java в IntelliJ IDEA

IntelliJ IDEA имеет встроенный декомпилятор Java, использующий FernFlower . Нам не нужно ничего устанавливать или настраивать, просто нажимаем на класс или метод Java, нажимаем CTRL + B (объявление или использование) или CTRL + ALT + B (реализация), IntelliJ IDEA автоматически декомпилирует класс Java.

4. Декомпилируйте класс Java в командной строке (цветок папоротника)

В этом примере показано, как использовать FernFlower (Java-декомпилятор) для декомпиляции .jar или .class файл в командной строке.

Примечание Размер официального Цветка папоротника немного велик, трудно построить источник. Обходной путь заключается в использовании зеркальной сборки fesh0r Fernflower .

4.1 клон git исходный код и Gradle встраивают исходный код в fernflower.jar

$ git clone https://github.com/fesh0r/fernflower $ cd fernflower # build the source code using Gradle build tool $ gradle build # the fernflower.jar at build/lib/

4.2 В приведенном ниже примере используется fernflower.jar для декомпиляции asm-analysis-3.2.jar Файл JAR в папку /путь/декомпилировать/ (должен существовать).

# decompile JAR or Class files # java -jar fernflower.jar /path/asm-analysis-3.2.jar /path/unknown.class /path/decompile/ $ java -jar fernflower.jar /path/asm-analysis-3.2.jar /path/decompile/ INFO: Decompiling class org/objectweb/asm/tree/analysis/Analyzer INFO: . done INFO: Decompiling class org/objectweb/asm/tree/analysis/AnalyzerException INFO: . done INFO: Decompiling class org/objectweb/asm/tree/analysis/BasicInterpreter INFO: . done

В результате получается новый /path/decompile/asm-analysis-3.2.jar содержащий исходный код *.java .

Извлеките декомпилированный файл JAR.

$ jar -xf /path/decompile/asm-analysis-3.2.jar

5. Рекомендации

Источник

Java.lang.Class class in Java | Set 1

Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are constructed automatically by the Java Virtual Machine(JVM). It is a final class, so we cannot extend it. The Class class methods are widely used in Reflection API.

In Java, the java.lang.Class class is a built-in class that represents a class or interface at runtime. It contains various methods that provide information about the class or interface, such as its name, superclass, interfaces, fields, and methods.

Here are some commonly used methods of the Class class:

  1. getName(): Returns the name of the class or interface represented by this Class object.
  2. getSimpleName(): Returns the simple name of the class or interface represented by this Class object.
  3. getSuperclass(): Returns the superclass of the class represented by this Class object.
  4. getInterfaces(): Returns an array of interfaces implemented by the class or interface represented by this Class object.
  5. getField(String name): Returns a Field object that represents the public field with the specified name in the class or interface represented by this Class object.
  6. getMethod(String name, Class… parameterTypes): Returns a Method object that represents the public method with the specified name and parameter types in the class or interface represented by this Class object.
  7. newInstance(): Creates a new instance of the class represented by this Class object using its default constructor.
  8. isInstance(Object obj): Returns true if the specified object is an instance of the class or interface represented by this Class object, false otherwise.
  9. isAssignableFrom(Class cls): Returns true if this Class object is assignable from the specified Class object, false otherwise.

Here’s an example of how to use some of these methods:

Java

System.out.println( «Is string assignable from Object? » + String. class .isAssignableFrom(Object. class ));

Name: java.lang.String Simple name: String Superclass: class java.lang.Object Interfaces: [] Is string assignable from Object? true

Creating a Class object

There are three ways to create Class object :

  1. Class.forName(“className”) : Since class Class doesn’t contain any constructor, there is static factory method present in class Class, which is Class.forName() , used for creating object of class Class. Below is the syntax :
Class c = Class.forName(String className)
  1. The above statement creates the Class object for the class passed as a String argument(className). Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time.
  2. Myclass.class : When we write .class after a class name, it references the Class object that represents the given class. It is mostly used with primitive data types and only when we know the name of class. The class name for which Class object is to be created is determined at compile-time. Below is the syntax :
A a = new A(); // Any class A Class c = A.class; // No error Class c = a.class; // Error
  1. obj.getClass(): This method is present in Object class. It return the run-time class of this(obj) object. Below is the syntax :
A a = new A(); // Any class A Class c = a.getClass();

Methods:

  1. String toString() : This method converts the Class object to a string. It returns the string representation which is the string “class” or “interface”, followed by a space, and then by the fully qualified name of the class. If the Class object represents a primitive type, then this method returns the name of the primitive type and if it represents void then it returns “void”.
Syntax : public String toString() Parameters : NA Returns : a string representation of this class object. Overrides : toString in class Object

Java

Class represented by c1: class java.lang.String Class represented by c2: int Class represented by c3: void
  1. Class forName(String className) : As discussed earlier, this method returns the Class object associated with the class or interface with the given string name. The other variant of this method is discussed next.
Syntax : public static Class forName(String className) throws ClassNotFoundException Parameters : className - the fully qualified name of the desired class. Returns : return the Class object for the class with the specified name. Throws : LinkageError : if the linkage fails ExceptionInInitializerError - if the initialization provoked by this method fails ClassNotFoundException - if the class cannot be located

Java

Class represented by c : class java.lang.String

Class forName(String className,boolean initialize, ClassLoader loader) : This method also returns the Class object associated with the class or interface with the given string name using the given class loader. The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader in. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.

Syntax : public static Class forName(String className,boolean initialize, ClassLoader loader) throws ClassNotFoundException Parameters : className - the fully qualified name of the desired class initialize - whether the class must be initialized loader - class loader from which the class must be loaded Returns : return the Class object for the class with the specified name. Throws : LinkageError : if the linkage fails ExceptionInInitializerError - if the initialization provoked by this method fails ClassNotFoundException - if the class cannot be located

Источник

Оцените статью