Skip to content

Instantly share code, notes, and snippets.

@jcaesar
Forked from rust-play/playground.rs
Last active October 21, 2020 00:20
Show Gist options
  • Save jcaesar/7557067e5a928f6bacc7bfcca6cb063d to your computer and use it in GitHub Desktop.
Save jcaesar/7557067e5a928f6bacc7bfcca6cb063d to your computer and use it in GitHub Desktop.
Get class path from java class file
fn main() -> anyhow::Result<()> {
println!("{}", get_name(include_bytes!("../Class.class"))?);
Ok(())
}
fn get_name(cf: &[u8]) -> anyhow::Result<String> {
use anyhow::Context;
use classfile_parser::constant_info::ConstantInfo::{Class, Utf8};
use classfile_parser::constant_info::ClassConstant;
let cf = match classfile_parser::class_parser(&cf) {
Ok((_, cf)) => cf,
Err(e) => anyhow::bail!("Invalid class file: {}", e)
};
let ci = cf
.const_pool
.get(cf.this_class as usize - 1)
.context(format!("this_class index {} out of bounds", cf.this_class))?;
let name_index = match ci {
Class(ClassConstant { name_index, .. }) => *name_index,
_ => anyhow::bail!(
"Expected a NameAndTypeConstant for this_class, found {:?}",
ci
)
};
let ci = cf.const_pool.get(name_index as usize - 1).context(format!(
"name_index for this_class {} out of bounds",
name_index
))?;
let s = match ci {
Utf8(s) => &s.utf8_string,
_ => anyhow::bail!(
"Expected a Utf8 constant for this_class' name, found {:?}",
ci
)
};
Ok(s.to_owned())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment