#Java - Code Snippets for '#Class' - 67 code snippet(s) found |
|
Sample 1. Example of Factory Class | |
|
public final class EmployeeFactory {
private Employee svEmp;
public EmployeeFactory(String type){
if( type.equals("Manager")){
svEmp = new Manager();
} else if(type.equals("Developer")){
svEmp = new Developer();
} else if(type.equals("QA")){
svEmp = new QA();
}
}
public Employee getFactoryProduct() {
return svEmp;
}
}
|
|
Like Feedback factory design pattern factory class final class composition |
|
|
Sample 2. Singleton Class ( using private constructor , object initialization using static method, doubly checked , thread safe, synchronized , volatile reference ) | |
|
class Singleton {
private static volatile Singleton instance = null;
private Singleton(){}
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance== null)
instance = new Singleton();
}
}
return instance;
}
}
|
|
Like Feedback singleton singleton class volatile private constructor object initialization using static method doubly checked thread safe synchronized block using class level lock synchronized synchronized block class level lock object initialization using getInstance |
|
|
Sample 3. Class Nested within Interface / Static Inner class within Interface | |
|
public interface SampleInterface {
public int sampleMethod(List sampleList);
static class Impl implements SampleInterface {
@Override
public int sampleMethod(List sampleList) {
return 0;
}
}
}
|
|
Like Feedback nested classes nested class inner class inner classes static inner class static inner class within interface @override |
|
|
Sample 4. Code Sample / Example / Snippet of org.apache.spark.ml.classification.LogisticRegressionModel | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext sqlContext = new SQLContext(jsc);
DataFrame training = sqlContext.read().format("libsvm")
.load("data/mllib/sample_libsvm_data.txt");
LogisticRegression lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.3)
.setElasticNetParam(0.8);
LogisticRegressionModel lrModel = lr.fit(training);
System.out.println("Coefficients: "
+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.classification.LogisticRegressionModel |
|
|
|
Sample 5. Declaring Abstract Class | |
|
public abstract class TestClass {
public static void main(String[] args){
}
}
|
|
Like Feedback abstract classes main method declaration main method |
|
|
Sample 6. Declaring static final ( constant ) variables. | |
|
public abstract class TestClass {
protected static final String TEST_STRING = "test";
public static void main(String[] args){
}
}
|
|
Like Feedback static final variables constant variables |
|
|
Sample 7. Interface Default Methods ( Base Class Definition has precedence over Interface Default Method if both are being extended and implemented and have common method definition ) | |
|
HelloJava8Base
public class HelloJava8Base {
public void defaultMethod() {
System.out.println("Default Method Base Class Implementation");
}
}
DefaultMethodInterface
public interface DefaultMethodInterface {
default public void defaultMethod() {
System.out.println("Default Method Interface Implementation");
}
}
HelloJava8
public class HelloJava8 extends HelloJava8Base implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface dmi = new HelloJava8();
dmi.defaultMethod(); // Prints "Default Method Base Class Implementation"
}
}
|
|
Like Feedback interface default methods java 8 interfaces |
|
|
Sample 8. Class bean with getter , setter and constructor | |
|
public class Employee {
public String name;
public int age;
public int salary;
Employee(String name, int age, int salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
|
|
Like Feedback bean pojo plain java objects getters setters getters nd setters classes class constructor parameterized constructor this keyword |
|
|
Sample 9. Load Properties using Property Class | |
|
private static Properties props = null;
private static void loadProperties(){
try {
if(props == null || props1 == null || props2 == null){
props = new Properties();
props.load(new FileInputStream(Constants.PROP_BASE_DIR + Constants.EMPLOYEE_REPORTING_PROP));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
|
Like Feedback property class properties FileInputStream file handling |
|
|
|
Sample 10. Method to check if the the file exists and not a directory | |
|
public static boolean isOleFile(File file)
{
if ((file == null) || (!file.exists()) || (file.isDirectory())) {
return false;
}
return true;
}
|
|
Like Feedback file handling check if file exists File class check if file is a directory file.isDirectory file.exists |
|
|
Sample 11. Code Sample / Example / Snippet of org.apache.bcel.classfile.AnnotationEntry | |
|
protected String dumpAnnotationEntries(final AnnotationEntry[] as)
{
final StringBuilder result = new StringBuilder();
result.append("[");
for (int i = 0; i < as.length; i++)
{
final AnnotationEntry annotation = as[i];
result.append(annotation.toShortString());
if (i + 1 < as.length) {
result.append(",");
}
}
result.append("]");
return result.toString();
}
|
|
Like Feedback org.apache.bcel.classfile.AnnotationEntry |
|
|
Sample 12. Code Sample / Example / Snippet of org.apache.bcel.classfile.Deprecated | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final Deprecated c = (Deprecated) clone();
if (bytes != null) {
c.bytes = new byte[bytes.length];
System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.Deprecated |
|
|
Sample 13. Code Sample / Example / Snippet of org.apache.bcel.classfile.Field | |
|
public void visitGETSTATIC(final GETSTATIC o) {
try {
final String field_name = o.getFieldName(cpg);
final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
final Field[] fields = jc.getFields();
Field f = null;
for (final Field field : fields) {
if (field.getName().equals(field_name)) {
f = field;
break;
}
}
if (f == null) {
throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
}
if (! (f.isStatic())) {
constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");
}
} catch (final ClassNotFoundException e) {
throw new AssertionViolatedException("Missing class: " + e, e);
}
}
|
|
Like Feedback org.apache.bcel.classfile.Field |
|
|
Sample 14. Declaring static block | |
|
public abstract class TestClass {
static{
init();
}
public static void main(String[] args){
}
private init(){
}
}
|
|
Like Feedback static block abstract class declaration |
|
|
|
Sample 15. Check if an object is an instanceOf class or derived class or implementing interface | |
|
DerivedClass dc = new DerivedClass();
if (dc instanceof BaseClass) {
}
|
|
Like Feedback instanceof |
|
|
Sample 16. Constant Class | |
|
public class Constants {
public static final long ZERO = 0L;
public static final long HUNDRED = 100L;
public static final long THOUSAND = 1000L;
}
|
|
Like Feedback constant class static final variable |
|
|
Sample 17. Database Api using java.sql classes | |
|
package BuggyBread;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseAPI {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "";
// Database credentials
static final String USER = "";
static final String PASS = "";
Connection conn = null;
public void initializeConnection(){
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try
}
}
|
|
Like Feedback database api java.sql |
|
|
Sample 18. Load Library | |
|
System.loadLibrary("jawt");
|
|
Like Feedback System Class system System.loadLibrary |
|
|
Sample 19. Loading Class using Class.forName ( Reflection ) | |
|
Class clazz = null;
try {
clazz = Class.forName("sun.awt.windows.WEmbeddedFrame");
} catch (Throwable e) {
}
Constructor constructor = null;
try {
constructor = clazz.getConstructor(new Class[] { Integer.TYPE });
} catch (Throwable localThrowable1) {
}
|
|
Like Feedback Class.forName Reflection |
|
|
|
Sample 20. Repeat a string using Google Guava Strings Class | |
|
System.out.println(Strings.repeat("Hello", 5));
|
|
Like Feedback google guava google guava string strings.repeat repeat characters repeat string |
|
|
Sample 21. Get the properties of class (i.e package name , interfaces , subclasses etc ) using ClassUtils( Apache Commons ) | |
|
Class class1 = ClassUtils.getClass("BuggyBreadTest");
System.out.println(ClassUtils.getPackageName(class1));
System.out.println(ClassUtils.getAllInterfaces(class1));
|
|
Like Feedback ClassUtils Apache Commons Get Class Properties java.lang.Class |
|
|
Sample 22. Code Sample / Example / Snippet of org.apache.spark.ml.classification.LogisticRegression | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext sqlContext = new SQLContext(jsc);
DataFrame training = sqlContext.read().format("libsvm")
.load("data/mllib/sample_libsvm_data.txt");
LogisticRegression lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.3)
.setElasticNetParam(0.8);
LogisticRegressionModel lrModel = lr.fit(training);
System.out.println("Coefficients: "
+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.classification.LogisticRegression |
|
|
Sample 23. Code Sample / Example / Snippet of org.apache.spark.mllib.classification.LogisticRegressionModel | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext sqlContext = new SQLContext(jsc);
DataFrame training = sqlContext.read().format("libsvm")
.load("data/mllib/sample_libsvm_data.txt");
LogisticRegression lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.3)
.setElasticNetParam(0.8);
LogisticRegressionModel lrModel = lr.fit(training);
System.out.println("Coefficients: "
+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());
jsc.stop();
}
|
|
Like Feedback org.apache.spark.mllib.classification.LogisticRegressionModel |
|
|
Sample 24. Code Sample / Example / Snippet of org.apache.bcel.classfile.AnnotationDefault | |
|
public void testMethodAnnotations() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");
final Method m = getMethod(clazz, "fruit");
final AnnotationDefault a = (AnnotationDefault) findAttribute(
"AnnotationDefault", m.getAttributes());
final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();
assertTrue("Should be STRING but is " + val.getElementValueType(), val
.getElementValueType() == ElementValue.STRING);
assertTrue("Should have default of bananas but default is "
+ val.getValueString(), val.getValueString().equals("bananas"));
}
|
|
Like Feedback org.apache.bcel.classfile.AnnotationDefault |
|
|
|
Sample 25. Code Sample / Example / Snippet of org.apache.bcel.classfile.Method | |
|
public void testMethodAnnotations() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");
final Method m = getMethod(clazz, "fruit");
final AnnotationDefault a = (AnnotationDefault) findAttribute(
"AnnotationDefault", m.getAttributes());
final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();
assertTrue("Should be STRING but is " + val.getElementValueType(), val
.getElementValueType() == ElementValue.STRING);
assertTrue("Should have default of bananas but default is "
+ val.getValueString(), val.getValueString().equals("bananas"));
}
|
|
Like Feedback org.apache.bcel.classfile.Method |
|
|
Sample 26. Code Sample / Example / Snippet of org.apache.bcel.classfile.SimpleElementValue | |
|
public void testMethodAnnotations() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");
final Method m = getMethod(clazz, "fruit");
final AnnotationDefault a = (AnnotationDefault) findAttribute(
"AnnotationDefault", m.getAttributes());
final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();
assertTrue("Should be STRING but is " + val.getElementValueType(), val
.getElementValueType() == ElementValue.STRING);
assertTrue("Should have default of bananas but default is "
+ val.getValueString(), val.getValueString().equals("bananas"));
}
|
|
Like Feedback org.apache.bcel.classfile.SimpleElementValue |
|
|
Sample 27. Code Sample / Example / Snippet of org.apache.bcel.classfile.JavaClass | |
|
public void testMethodAnnotations() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");
final Method m = getMethod(clazz, "fruit");
final AnnotationDefault a = (AnnotationDefault) findAttribute(
"AnnotationDefault", m.getAttributes());
final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();
assertTrue("Should be STRING but is " + val.getElementValueType(), val
.getElementValueType() == ElementValue.STRING);
assertTrue("Should have default of bananas but default is "
+ val.getValueString(), val.getValueString().equals("bananas"));
}
|
|
Like Feedback org.apache.bcel.classfile.JavaClass |
|
|
Sample 28. Code Sample / Example / Snippet of org.apache.bcel.classfile.Attribute | |
|
protected String dumpAttributes(final Attribute[] as)
{
final StringBuilder result = new StringBuilder();
result.append("AttributeArray:[");
for (int i = 0; i < as.length; i++)
{
final Attribute attr = as[i];
result.append(attr.toString());
if (i + 1 < as.length) {
result.append(",");
}
}
result.append("]");
return result.toString();
}
|
|
Like Feedback org.apache.bcel.classfile.Attribute |
|
|
Sample 29. Code Sample / Example / Snippet of org.apache.bcel.generic.ClassGen | |
|
public void testCreateIntegerElementValue() throws Exception
{
final ClassGen cg = createClassGen("HelloWorld");
final ConstantPoolGen cp = cg.getConstantPool();
final SimpleElementValueGen evg = new SimpleElementValueGen(
ElementValueGen.PRIMITIVE_INT, cp, 555);
assertTrue("Should have the same index in the constantpool but "
+ evg.getIndex() + "!=" + cp.lookupInteger(555),
evg.getIndex() == cp.lookupInteger(555));
checkSerialize(evg, cp);
}
|
|
Like Feedback org.apache.bcel.generic.ClassGen |
|
|
|
Sample 30. Code Sample / Example / Snippet of org.apache.bcel.generic.ClassElementValueGen | |
|
public void testCreateClassElementValue() throws Exception
{
final ClassGen cg = createClassGen("HelloWorld");
final ConstantPoolGen cp = cg.getConstantPool();
final ObjectType classType = new ObjectType("java.lang.Integer");
final ClassElementValueGen evg = new ClassElementValueGen(classType, cp);
assertTrue("Unexpected value for contained class: '"
+ evg.getClassString() + "'", evg.getClassString().contains("Integer"));
checkSerialize(evg, cp);
}
|
|
Like Feedback org.apache.bcel.generic.ClassElementValueGen |
|
|
Sample 31. Code Sample / Example / Snippet of org.apache.bcel.classfile.EnclosingMethod | |
|
public void testCheckMethodLevelNamedInnerClass()
throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S");
final ConstantPool pool = clazz.getConstantPool();
final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);
assertTrue("Expected 1 EnclosingMethod attribute but found "
+ encMethodAttrs.length, encMethodAttrs.length == 1);
final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];
final String enclosingClassName = em.getEnclosingClass().getBytes(pool);
final String enclosingMethodName = em.getEnclosingMethod().getName(pool);
assertTrue(
"Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was "
+ enclosingClassName, enclosingClassName
.equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01"));
assertTrue("Expected method name to be 'main' but was "
+ enclosingMethodName, enclosingMethodName.equals("main"));
}
|
|
Like Feedback org.apache.bcel.classfile.EnclosingMethod |
|
|
Sample 32. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantPool | |
|
public void testCheckMethodLevelNamedInnerClass()
throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S");
final ConstantPool pool = clazz.getConstantPool();
final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);
assertTrue("Expected 1 EnclosingMethod attribute but found "
+ encMethodAttrs.length, encMethodAttrs.length == 1);
final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];
final String enclosingClassName = em.getEnclosingClass().getBytes(pool);
final String enclosingMethodName = em.getEnclosingMethod().getName(pool);
assertTrue(
"Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was "
+ enclosingClassName, enclosingClassName
.equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01"));
assertTrue("Expected method name to be 'main' but was "
+ enclosingMethodName, enclosingMethodName.equals("main"));
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantPool |
|
|
Sample 33. Code Sample / Example / Snippet of org.apache.bcel.classfile.ArrayElementValue | |
|
private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno)
{
final ElementValuePair elementValuePair = anno.getElementValuePairs()[0];
assertEquals("value", elementValuePair.getNameString());
final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue();
final ElementValue[] eva = ev.getElementValuesArray();
assertEquals(nExpectedArrayValues, eva.length);
}
|
|
Like Feedback org.apache.bcel.classfile.ArrayElementValue |
|
|
Sample 34. Code Sample / Example / Snippet of org.apache.bcel.classfile.ElementValuePair | |
|
private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno)
{
final ElementValuePair elementValuePair = anno.getElementValuePairs()[0];
assertEquals("value", elementValuePair.getNameString());
final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue();
final ElementValue[] eva = ev.getElementValuesArray();
assertEquals(nExpectedArrayValues, eva.length);
}
|
|
Like Feedback org.apache.bcel.classfile.ElementValuePair |
|
|
|
Sample 35. Code Sample / Example / Snippet of org.apache.bcel.classfile.ClassParser | |
|
private void testJar(final File file) throws Exception {
System.out.println(file);
try (JarFile jar = new JarFile(file)) {
final Enumeration<JarEntry> en = jar.entries();
while (en.hasMoreElements()) {
final JarEntry e = en.nextElement();
final String name = e.getName();
if (name.endsWith(".class")) {
try (InputStream in = jar.getInputStream(e)) {
final ClassParser parser = new ClassParser(in, name);
final JavaClass jc = parser.parse();
for (final Method m : jc.getMethods()) {
compare(name, m);
}
}
}
}
}
}
|
|
Like Feedback org.apache.bcel.classfile.ClassParser |
|
|
Sample 36. Code Sample / Example / Snippet of org.apache.bcel.classfile.Code | |
|
private void compare(final String name, final Method m) {
final Code c = m.getCode();
if (c == null) {
return; // e.g. abstract method
}
final byte[] src = c.getCode();
final InstructionList il = new InstructionList(src);
final byte[] out = il.getByteCode();
if (src.length == out.length) {
assertArrayEquals(name + ": " + m.toString(), src, out);
} else {
System.out.println(name + ": " + m.toString() + " " + src.length + " " + out.length);
System.out.println(bytesToHex(src));
System.out.println(bytesToHex(out));
for (final InstructionHandle ih : il) {
System.out.println(ih.toString(false));
}
fail("Array comparison failure");
}
}
|
|
Like Feedback org.apache.bcel.classfile.Code |
|
|
Sample 37. Code Sample / Example / Snippet of org.apache.bcel.classfile.LocalVariableTable | |
|
public void testB79() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass");
final ClassGen gen = new ClassGen(clazz);
final ConstantPoolGen pool = gen.getConstantPool();
final Method m = gen.getMethodAt(2);
final LocalVariableTable lvt = m.getLocalVariableTable();
final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());
assertEquals("number of locals", lvt.getTableLength(), new_lvt.getTableLength());
}
|
|
Like Feedback org.apache.bcel.classfile.LocalVariableTable |
|
|
Sample 38. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantUtf8 | |
|
public static String[] getClassDependencies(ConstantPool pool) {
String[] tempArray = new String[pool.getLength()];
int size = 0;
StringBuilder buf = new StringBuilder();
for (int idx = 0; idx < pool.getLength(); idx++) {
Constant c = pool.getConstant(idx);
if (c != null && c.getTag() == Constants.CONSTANT_Class) {
ConstantUtf8 c1 = (ConstantUtf8) pool.getConstant(((ConstantClass) c).getNameIndex());
buf.setLength(0);
buf.append(c1.getBytes());
for (int n = 0; n < buf.length(); n++) {
if (buf.charAt(n) == '/') {
buf.setCharAt(n, '.');
}
}
tempArray[size++] = buf.toString();
}
}
String[] dependencies = new String[size];
System.arraycopy(tempArray, 0, dependencies, 0, size);
return dependencies;
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantUtf8 |
|
|
Sample 39. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantNameAndType | |
|
private void visitRef(ConstantCP ccp, boolean method) {
String class_name = ccp.getClass(cp);
add(class_name);
ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(ccp.getNameAndTypeIndex(),
Constants.CONSTANT_NameAndType);
String signature = cnat.getSignature(cp);
if (method) {
Type type = Type.getReturnType(signature);
checkType(type);
for (Type type1 : Type.getArgumentTypes(signature)) {
checkType(type1);
}
} else {
checkType(Type.getType(signature));
}
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantNameAndType |
|
|
|
Sample 40. Code Sample / Example / Snippet of org.apache.bcel.util.ClassPath | |
|
public static ClassPath.ClassFile lookupClassFile( final String class_name ) {
try {
final ClassPath path = repository.getClassPath();
if (path == null) {
return null;
}
return path.getClassFile(class_name);
} catch (final IOException e) {
return null;
}
}
|
|
Like Feedback org.apache.bcel.util.ClassPath |
|
|
Sample 41. Code Sample / Example / Snippet of org.apache.bcel.classfile.Constant | |
|
public String getEnumTypeString()
{
return ((ConstantUtf8) getConstantPool().getConstant(typeIdx))
.getBytes();
}
|
|
Like Feedback org.apache.bcel.classfile.Constant |
|
|
Sample 42. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantInteger | |
|
public int getValueInt()
{
if (super.getElementValueType() != PRIMITIVE_INT) {
throw new RuntimeException(
"Dont call getValueString() on a non STRING ElementValue");
}
final ConstantInteger c = (ConstantInteger) getConstantPool().getConstant(idx);
return c.getBytes();
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantInteger |
|
|
Sample 43. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantClass | |
|
public String getEnumTypeString()
{
return ((ConstantUtf8) getConstantPool().getConstant(typeIdx))
.getBytes();
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantClass |
|
|
Sample 44. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantCP | |
|
public String getClassName( final ConstantPoolGen cpg ) {
final ConstantPool cp = cpg.getConstantPool();
final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
final String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class);
if (className.startsWith("[")) {
return "java.lang.Object";
}
return className.replace('/', '.');
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantCP |
|
|
|
Sample 45. Code Sample / Example / Snippet of org.apache.bcel.classfile.Annotations | |
|
public FieldGen(final Field field, final ConstantPoolGen cp) {
this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp);
final Attribute[] attrs = field.getAttributes();
for (final Attribute attr : attrs) {
if (attr instanceof ConstantValue) {
setValue(((ConstantValue) attr).getConstantValueIndex());
} else if (attr instanceof Annotations) {
final Annotations runtimeAnnotations = (Annotations)attr;
final AnnotationEntry[] annotationEntries = runtimeAnnotations.getAnnotationEntries();
for (final AnnotationEntry element : annotationEntries) {
addAnnotationEntry(new AnnotationEntryGen(element,cp,false));
}
} else {
addAttribute(attr);
}
}
}
|
|
Like Feedback org.apache.bcel.classfile.Annotations |
|
|
Sample 46. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantFloat | |
|
public int lookupFloat( final float n ) {
final int bits = Float.floatToIntBits(n);
for (int i = 1; i < index; i++) {
if (constants[i] instanceof ConstantFloat) {
final ConstantFloat c = (ConstantFloat) constants[i];
if (Float.floatToIntBits(c.getBytes()) == bits) {
return i;
}
}
}
return -1;
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantFloat |
|
|
Sample 47. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantString | |
|
public String stringifyValue()
{
final ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(valueIdx);
return cu8.getBytes();
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantString |
|
|
Sample 48. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantLong | |
|
public int lookupLong( final long n ) {
for (int i = 1; i < index; i++) {
if (constants[i] instanceof ConstantLong) {
final ConstantLong c = (ConstantLong) constants[i];
if (c.getBytes() == n) {
return i;
}
}
}
return -1;
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantLong |
|
|
Sample 49. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantDouble | |
|
public int lookupDouble( final double n ) {
final long bits = Double.doubleToLongBits(n);
for (int i = 1; i < index; i++) {
if (constants[i] instanceof ConstantDouble) {
final ConstantDouble c = (ConstantDouble) constants[i];
if (Double.doubleToLongBits(c.getBytes()) == bits) {
return i;
}
}
}
return -1;
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantDouble |
|
|
|
Sample 50. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantValue | |
|
public void visitField( final Field field ) {
_out.println();
_out.println(" field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", "
+ printType(field.getSignature()) + ", "" + field.getName() + "", _cp);");
final ConstantValue cv = field.getConstantValue();
if (cv != null) {
final String value = cv.toString();
_out.println(" field.setInitValue(" + value + ")");
}
_out.println(" _cg.addField(field.getField());");
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantValue |
|
|
Sample 51. Code Sample / Example / Snippet of org.apache.bcel.util.ClassQueue | |
|
public JavaClass[] getAllInterfaces() throws ClassNotFoundException {
final ClassQueue queue = new ClassQueue();
final Set<JavaClass> allInterfaces = new TreeSet<>();
queue.enqueue(this);
while (!queue.empty()) {
final JavaClass clazz = queue.dequeue();
final JavaClass souper = clazz.getSuperClass();
final JavaClass[] _interfaces = clazz.getInterfaces();
if (clazz.isInterface()) {
allInterfaces.add(clazz);
} else {
if (souper != null) {
queue.enqueue(souper);
}
}
for (final JavaClass _interface : _interfaces) {
queue.enqueue(_interface);
}
}
return allInterfaces.toArray(new JavaClass[allInterfaces.size()]);
}
|
|
Like Feedback org.apache.bcel.util.ClassQueue |
|
|
Sample 52. Code Sample / Example / Snippet of org.apache.bcel.classfile.MethodParameters | |
|
public Attribute copy(final ConstantPool _constant_pool) {
final MethodParameters c = (MethodParameters) clone();
c.parameters = new MethodParameter[parameters.length];
for (int i = 0; i < parameters.length; i++) {
c.parameters[i] = parameters[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.MethodParameters |
|
|
Sample 53. Code Sample / Example / Snippet of org.apache.bcel.classfile.BootstrapMethods | |
|
public BootstrapMethods copy(final ConstantPool _constant_pool) {
final BootstrapMethods c = (BootstrapMethods) clone();
c.bootstrap_methods = new BootstrapMethod[bootstrap_methods.length];
for (int i = 0; i < bootstrap_methods.length; i++) {
c.bootstrap_methods[i] = bootstrap_methods[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.BootstrapMethods |
|
|
Sample 54. Code Sample / Example / Snippet of org.apache.bcel.classfile.InnerClasses | |
|
public Attribute copy(final ConstantPool _constant_pool) {
final InnerClasses c = (InnerClasses) clone();
c.inner_classes = new InnerClass[inner_classes.length];
for (int i = 0; i < inner_classes.length; i++) {
c.inner_classes[i] = inner_classes[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.InnerClasses object initialization using clone |
|
|
|
Sample 55. Code Sample / Example / Snippet of org.apache.bcel.classfile.Synthetic | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final Synthetic c = (Synthetic) clone();
if (bytes != null) {
c.bytes = new byte[bytes.length];
System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.Synthetic |
|
|
Sample 56. Code Sample / Example / Snippet of org.apache.bcel.classfile.LocalVariableTypeTable | |
|
public Attribute copy(final ConstantPool constant_pool) {
final LocalVariableTypeTable c = (LocalVariableTypeTable) clone();
c.local_variable_type_table = new LocalVariable[local_variable_type_table.length];
for (int i = 0; i < local_variable_type_table.length; i++) {
c.local_variable_type_table[i] = local_variable_type_table[i].copy();
}
c.setConstantPool(constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.LocalVariableTypeTable |
|
|
Sample 57. Code Sample / Example / Snippet of org.apache.bcel.classfile.Node | |
|
public void jjtAddChild(Node n, int i) {
if (children == null) {
children = new Node[i + 1];
} else if (i >= children.length) {
Node c[] = new Node[i + 1];
System.arraycopy(children, 0, c, 0, children.length);
children = c;
}
children[i] = n;
}
|
|
Like Feedback org.apache.bcel.classfile.Node |
|
|
Sample 58. Code Sample / Example / Snippet of org.apache.bcel.classfile.ParameterAnnotations | |
|
public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final Attribute[] attrs) {
final List<ParameterAnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length);
for (final Attribute attribute : attrs) {
if (attribute instanceof ParameterAnnotations) {
final ParameterAnnotations runtimeAnnotations = (ParameterAnnotations)attribute;
Collections.addAll(accumulatedAnnotations, runtimeAnnotations.getParameterAnnotationEntries());
}
}
return accumulatedAnnotations.toArray(new ParameterAnnotationEntry[accumulatedAnnotations.size()]);
}
|
|
Like Feedback org.apache.bcel.classfile.ParameterAnnotations |
|
|
Sample 59. Code Sample / Example / Snippet of org.apache.bcel.classfile.Unknown | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final Unknown c = (Unknown) clone();
if (bytes != null) {
c.bytes = new byte[bytes.length];
System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.Unknown |
|
|
|
Sample 60. Code Sample / Example / Snippet of org.apache.bcel.classfile.StackMap | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final StackMap c = (StackMap) clone();
c.map = new StackMapEntry[map.length];
for (int i = 0; i < map.length; i++) {
c.map[i] = map[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.StackMap |
|
|
Sample 61. Code Sample / Example / Snippet of org.apache.bcel.classfile.LineNumberTable | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final LineNumberTable c = (LineNumberTable) clone();
c.line_number_table = new LineNumber[line_number_table.length];
for (int i = 0; i < line_number_table.length; i++) {
c.line_number_table[i] = line_number_table[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.LineNumberTable |
|
|
Sample 62. Code Sample / Example / Snippet of org.apache.bcel.classfile.DescendingVisitor | |
|
private void field_and_method_refs_are_valid() {
try {
final JavaClass jc = Repository.lookupClass(myOwner.getClassName());
final DescendingVisitor v = new DescendingVisitor(jc, new FAMRAV_Visitor(jc));
v.visit();
} catch (final ClassNotFoundException e) {
throw new AssertionViolatedException("Missing class: " + e, e);
}
}
|
|
Like Feedback org.apache.bcel.classfile.DescendingVisitor |
|
|
Sample 63. Usage of Builder Class / Builder Pattern | |
|
public class BuggyBread {
private String element1; // Make them private as it supports stronger encapsulation
private String element2;
private BuggyBread(String element1, String element2){ // Make it private so that it can only be used by Builder
this.element1 = element1;
this.element2 = element2;
}
public static class Builder {
// Create Builder as nested class as its only supposed to Build BuggyBread objects,
// Make it public so that it can be accessed from outside
private String element1; // Make them private as it supports stronger encapsulation
private String element2;
Builder(){}; // We have to define this constructor if we need overloaded constructor too and need to initialize without arguments too
Builder(BuggyBread buggybread){ // overloaded constructor to make things easy
element1 = buggybread.element1;
element2 = buggybread.element2;
}
Builder withElement1(String element1){ // Builder method to either populate elements or override ( if populated through overloaded constructor )
this.element1 = element1;
return this;
}
Builder withElement2(String element2){
this.element2 = element2;
return this;
}
BuggyBread build(){ // method to build BuggyBread object using final contents from Builder
BuggyBread buggybread = new BuggyBread(element1,element2);
return buggybread;
}
}
}
|
|
Like Feedback builder pattern builder class |
|
|
Sample 64. Write a Program to show Java thread usage by extending Thread class | |
|
public class MyClass {
static class MyThreadClass extends Thread{
@Override
public void run() {
System.out.println("Hello");
try {
Thread.sleep(1000);
System.out.println("Hello Again");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
MyThreadClass myThreadClass = new MyThreadClass();
myThreadClass.start();
MyThreadClass myThreadClass2 = new MyThreadClass();
myThreadClass2.start();
}
}
|
|
Like Feedback Threads Thread class |
|
|
|
Sample 65. Code to get Module name for the class | |
|
Module module = Test.class.getModule();
System.out.println(module.getName());
|
|
Like Feedback java 9 java 9 module |
|
|
Sample 66. Code to get Module name for List class | |
|
Module module = java.util.List.class.getModule();
System.out.println(module.getName()); // prints java.base
|
|
Like Feedback java 9 java 9 module |
|
|
Sample 67. Code to get main class in a particular module | |
|
Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();
System.out.println(moduleDescriptor.mainClass());
|
|
Like Feedback java 9 java 9 modules get main class for a module get main class for a module in java 9 java module |
|
|