Редактирование class файлов java

Как изменить уже скомпилированный файл .class без декомпиляции?

Я хочу изменить метод .class file. Я установил JD Eclipse Decompiler и открыл файл .class. Я добавил несколько кодов и сохранил файл .class. Но файл .class не меняется. Я не знаю, как использовать декомпилятор. И если это возможно, как изменить файл .class без использования декомпилятора. Я использую Ubuntu. Привет EDIT: Вот мой декомпилированный код:

/* */ package org.hibernate.id; /* */ /* */ import java.io.Serializable; /* */ import java.sql.ResultSet; /* */ import java.sql.SQLException; /* */ import java.util.HashMap; /* */ import java.util.Properties; /* */ import org.apache.commons.logging.Log; /* */ import org.apache.commons.logging.LogFactory; /* */ import org.hibernate.HibernateException; /* */ import org.hibernate.MappingException; /* */ import org.hibernate.dialect.Dialect; /* */ import org.hibernate.type.Type; /* */ import org.hibernate.util.ReflectHelper; /* */ /* */ public final class IdentifierGeneratorFactory /* */ < /* 25 */ private static final Log log = LogFactory.getLog(IdentifierGeneratorFactory.class); /* */ /* 64 */ private static final HashMap GENERATORS = new HashMap(); /* */ /* 66 */ public static final Serializable SHORT_CIRCUIT_INDICATOR = new Serializable() < /* */ public String toString() < return "SHORT_CIRCUIT_INDICATOR"; /* */ >/* 66 */ >; /* */ /* 70 */ public static final Serializable POST_INSERT_INDICATOR = new Serializable() < /* */ public String toString() < return "POST_INSERT_INDICATOR"; /* */ >/* 70 */ >; /* */ /* */ public static Serializable getGeneratedIdentity(ResultSet rs, Type type) /* */ throws SQLException, HibernateException, IdentifierGenerationException /* */ < /* 32 */ if (!(rs.next())) < /* 33 */ throw new HibernateException("The database returned no natively generated identity value"); /* */ >/* 35 */ Serializable type); /* */ /* 37 */ if (log.isDebugEnabled()) log.debug("Natively generated identity: " + id); /* 38 */ return id; /* */ > /* */ /* */ public static Serializable get(ResultSet rs, Type type) /* */ throws SQLException, IdentifierGenerationException /* */ < /* 45 */ Class clazz = type.getReturnedClass(); /* 46 */ if (clazz == Long.class) < /* 47 */ return new Long(rs.getLong(1)); /* */ >/* 49 */ if (clazz == Integer.class) < /* 50 */ return new Integer(rs.getInt(1)); /* */ >/* 52 */ if (clazz == Short.class) < /* 53 */ return new Short(rs.getShort(1)); /* */ >/* 55 */ if (clazz == String.class) < /* 56 */ return rs.getString(1); /* */ >if(clazz == java.math.BigDecimal.class) < return rs.getBigDecimal(1); >/* */ /* 59 */ throw new IdentifierGenerationException("this id generator generates long, integer, short or string78"); /* */ > /* */ /* */ public static IdentifierGenerator create(String strategy, Type type, Properties params, Dialect dialect) /* */ throws MappingException /* */ < /* */ try /* */ < /* 92 */ Class clazz = getIdentifierGeneratorClass(strategy, dialect); /* 93 */ IdentifierGenerator idgen = (IdentifierGenerator)clazz.newInstance(); /* 94 */ if (idgen instanceof Configurable) ((Configurable)idgen).configure(type, params, dialect); /* 95 */ return idgen; /* */ >/* */ catch (Exception e) < /* 98 */ throw new MappingException("could not instantiate id generator", e); /* */ >/* */ > /* */ /* */ public static Class getIdentifierGeneratorClass(String strategy, Dialect dialect) < /* 103 */ Class clazz = (Class)GENERATORS.get(strategy); /* 104 */ if ("native".equals(strategy)) clazz = dialect.getNativeIdentifierGeneratorClass(); /* */ try < /* 106 */ if (clazz == null) clazz = ReflectHelper.classForName(strategy); /* */ >/* */ catch (ClassNotFoundException e) < /* 109 */ throw new MappingException("could not interpret id generator strategy: " + strategy); /* */ >/* 111 */ return clazz; /* */ > /* */ /* */ public static Number createNumber(long value, Class clazz) throws IdentifierGenerationException < /* 115 */ if (clazz == Long.class) < /* 116 */ return new Long(value); /* */ >/* 118 */ if (clazz == Integer.class) < /* 119 */ return new Integer((int)value); /* */ >/* 121 */ if (clazz == Short.class) < /* 122 */ return new Short((short)(int)value); /* */ >/* */ /* 125 */ throw new IdentifierGenerationException("this id generator generates long, integer, short"); /* */ > /* */ /* */ static /* */ < /* 75 */ GENERATORS.put("uuid", UUIDHexGenerator.class); GENERATORS.put("hilo", TableHiLoGenerator.class); GENERATORS.put("assigned", Assigned.class); GENERATORS.put("identity", IdentityGenerator.class); GENERATORS.put("select", SelectGenerator.class); GENERATORS.put("sequence", SequenceGenerator.class); GENERATORS.put("seqhilo", SequenceHiLoGenerator.class); GENERATORS.put("increment", IncrementGenerator.class); GENERATORS.put("foreign", ForeignGenerator.class); GENERATORS.put("guid", GUIDGenerator.class); GENERATORS.put("uuid.hex", UUIDHexGenerator.class); GENERATORS.put("sequence-identity", SequenceIdentityGenerator.class); >> 

Потому что класс idgenerator не поддерживает BigDecimal. Я использую Hibernate и PostgreSQL и получаю эту ошибку: этот генератор идентификаторов генерирует long, integer, short или string

Читайте также:  Python change case string

Использование декомпилятора в 100 раз проще, чем альтернативы. Если вы найдете идею использовать декомпилятор немного, я бы попробовал другой подход, который не включает в себя изменение класса.

Источник

Class File Editor in Java

Class File Editor in Java

  1. Features of Java Class File Editor
  2. Using Java Class File Editor to Edit a Compiled Java Class

In this article, we will discuss the Java Class File Editor, a tool created in Java used to edit Java compiled classes. We can decompile and see the Java classes once they are created, but we need tools like the Java Class File Editor to modify them.

Features of Java Class File Editor

  • Easy to use Interface built using Java Swing
  • Allows modifications of various parts of a class file, like methods, strings, constants, etc.
  • Consistency Checks

Using Java Class File Editor to Edit a Compiled Java Class

Download Java Class File Editor from https://sourceforge.net/projects/classeditor/files/
Extract the compressed file, and open the JAR file name ce.jar shown below.

Class File Editor in Java - Step 2

If we are unable to open the file, we can open the command line/terminal and use the following command:

Once the editor is opened, we open a Java class file using the File > Open menu item and choose the explorer class file.
We will use the following code in the class file.
public class ExampleClass1   private static final String METHOD_NAME1 = "exampleMethod1";  private static final String METHOD_NAME2 = "exampleMethod2";   public static void main(String[] args)   int abc = 200;  System.out.println(abc);  exampleMethod2();   >   static void exampleMethod2()   System.out.println("This is just a method");  >  > 
After the editor opens the file, we turn on the Modify Mode in the top-right corner; this mode is off by default, as shown in the image below. The button will turn blue if it is on and green if it is off.

Class File Editor in Java - Step 5

After the modification is on, we can modify certain aspects of the class by going to different editor sections.

The General section of the editor shows the class name and its parent class. We can see and edit the interfaces if any are in the class. Class Access Modifiers are also there, which we can change if we want to.
Class File Editor in Java - Step 6
The next section is the Constant Pool section, which displays all the editor’s constants in the class. Here we can change the type of the constant and its value. We can add new constants or delete an existing one.
Class File Editor in Java - Step 6
The Fields section of the editor shows the fields with their access modifiers which we can modify.
Class File Editor in Java - Step 6
The last section of the editor part is the Methods section, where all the class methods are listed with their name, access modifiers, and return types that are all editable, and we can change them.
Class File Editor in Java - Step 2

After all the modifications, we save the class file using the File > Save menu item. We can also export all the items like the name of fields, constants, methods, and their values as an XML file using the File > Export to XML menu item.

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Источник

Как редактировать .class файлы из архивов Jar

вц.jpg

Собственно, перерыл весь интернет, и никак не пойму. как отредактировать вот эти переменные в файле .class

В программе Recaf даже редактировать могу, но не сохраняется при экспорте. Пробовал Эклипс — там вообще нет возможности редактировать (или я не нашел). В интернете нашел Java ByteCod Editor и DirtyJoe, у них получается редактировать только методы. А вот эти строчки переменные редактировать там возможности нет.
Подскажите, пожалуйста, чем и как редактировать эти переменные, выделенные на фото?

Deom

Пляшущий с бубном

Собственно, перерыл весь интернет, и никак не пойму. как отредактировать вот эти переменные в файле .class
Посмотреть вложение 37913

В программе Recaf даже редактировать могу, но не сохраняется при экспорте. Пробовал Эклипс — там вообще нет возможности редактировать (или я не нашел). В интернете нашел Java ByteCod Editor и DirtyJoe, у них получается редактировать только методы. А вот эти строчки переменные редактировать там возможности нет.
Подскажите, пожалуйста, чем и как редактировать эти переменные, выделенные на фото?

class — это скомпилированный файл. Его редактирование не допустимо. Тебе нужно для начала декомпилировать сборку, потом отдельно собирать класс и добавлять его с заменой старого в свой jar файл через WinRar.

Источник

Как изменить class файл java

Исходный код, написанный на Java и сохраненный в файл с расширением .java, с помощью компилятора Javac компилируется в байт-код и сохраняется в двоичный файл с расширением .class для дальнейшего запуска на JVM (Java Virtual Machine).

Это исходный код Java в файле с расширением .java

public class MainClass  public static void main(String[] args)  System.out.println("Hello world!"); > > 

Это скомпилированный исходный код компилятором Javac и сохраненный в файл с расширением .class:

  
Никита Сысоев
06 октября 2022

В Java class файл представляет из себя файл с байт-кодом. Для его изменения достаточно внести изменение в исходный код, а затем скомпилировать его. Это можно сделать в среде разработки, нажав на зеленый треугольник, или вручную, запустив приложение-компилятор.

// Компилируем измененный файл с исходным кодом javac Main.java 

Появится файл с именем Main.class . Этот файл представляет из себя байт-код, сгенерированный компилятором. Запускаем этот файл, т.е. нашу программу, внутри JVM .

Источник

Java Class File Editor

Open a Java class file binary to view or edit strings, attributes, methods and generate readable reports similar to the javap utility. In built verifier checks changes before saving the file. Easy to use Java Swing GUI.

Project Samples

ClassEditor Constant Pool Display ClassEditor Byte Code Display ClassEditor Methods Screen

Project Activity

Categories

License

Follow Java Class File Editor

Open LMS is Open Source at its core. Migrating to Open LMS is simple and easy.

As the largest commercial provider of hosting and support services for the open-source Moodle™ learning platform, we help organizations and institutions deliver great learning experiences without complexities

User Ratings

User Reviews

Additional Project Details

Languages

Intended Audience

Programming Language

Registered

The Java™ Programming Language is a general-purpose, concurrent, strongly typed, class-based object-oriented language. It is normally compiled to the bytecode instruction set and binary format defined in the Java Virtual Machine Specification. In the Java programming language, all source code is.

Rapise is a robust, next-generation test automation platform for desktop, mobile, and web applications developed by Inflectra. Using the power of open and extensible architecture, Rapise delivers the most rapid and flexible functional testing tool. Rapise comes with a built-in support for.

PSPDFKit is the comprehensive solution for all your PDF needs, offering tools that effortlessly integrate and operate PDF functionality across any platform. 1. SDK PRODUCTS Integrate robust PDF functionality into iOS, Android, Windows, web (JavaScript), or any cross-platform technology.

Источник

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